diff --git a/.librarian/state.yaml b/.librarian/state.yaml index c2cf7c96e468..09b2bbb7d5a7 100644 --- a/.librarian/state.yaml +++ b/.librarian/state.yaml @@ -954,10 +954,12 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-ces version: 0.0.0 - last_generated_commit: dc505966accc82576fc1ebed3d7924fe9df4ab49 + last_generated_commit: 69bf99a9d0910fa86c3c5867ea357aa004dfcc55 apis: - path: google/cloud/ces/v1 service_config: ces_v1.yaml + - path: google/cloud/ces/v1beta + service_config: ces_v1beta.yaml source_roots: - packages/google-cloud-ces preserve_regex: diff --git a/packages/google-cloud-ces/docs/ces_v1beta/agent_service.rst b/packages/google-cloud-ces/docs/ces_v1beta/agent_service.rst new file mode 100644 index 000000000000..d4dbd7a27104 --- /dev/null +++ b/packages/google-cloud-ces/docs/ces_v1beta/agent_service.rst @@ -0,0 +1,10 @@ +AgentService +------------------------------ + +.. automodule:: google.cloud.ces_v1beta.services.agent_service + :members: + :inherited-members: + +.. automodule:: google.cloud.ces_v1beta.services.agent_service.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-ces/docs/ces_v1beta/evaluation_service.rst b/packages/google-cloud-ces/docs/ces_v1beta/evaluation_service.rst new file mode 100644 index 000000000000..492264677662 --- /dev/null +++ b/packages/google-cloud-ces/docs/ces_v1beta/evaluation_service.rst @@ -0,0 +1,10 @@ +EvaluationService +----------------------------------- + +.. automodule:: google.cloud.ces_v1beta.services.evaluation_service + :members: + :inherited-members: + +.. automodule:: google.cloud.ces_v1beta.services.evaluation_service.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-ces/docs/ces_v1beta/services_.rst b/packages/google-cloud-ces/docs/ces_v1beta/services_.rst new file mode 100644 index 000000000000..0d9075384160 --- /dev/null +++ b/packages/google-cloud-ces/docs/ces_v1beta/services_.rst @@ -0,0 +1,10 @@ +Services for Google Cloud Ces v1beta API +======================================== +.. toctree:: + :maxdepth: 2 + + agent_service + evaluation_service + session_service + tool_service + widget_service diff --git a/packages/google-cloud-ces/docs/ces_v1beta/session_service.rst b/packages/google-cloud-ces/docs/ces_v1beta/session_service.rst new file mode 100644 index 000000000000..9a1a92fbde48 --- /dev/null +++ b/packages/google-cloud-ces/docs/ces_v1beta/session_service.rst @@ -0,0 +1,6 @@ +SessionService +-------------------------------- + +.. automodule:: google.cloud.ces_v1beta.services.session_service + :members: + :inherited-members: diff --git a/packages/google-cloud-ces/docs/ces_v1beta/tool_service.rst b/packages/google-cloud-ces/docs/ces_v1beta/tool_service.rst new file mode 100644 index 000000000000..418f30befebd --- /dev/null +++ b/packages/google-cloud-ces/docs/ces_v1beta/tool_service.rst @@ -0,0 +1,6 @@ +ToolService +----------------------------- + +.. automodule:: google.cloud.ces_v1beta.services.tool_service + :members: + :inherited-members: diff --git a/packages/google-cloud-ces/docs/ces_v1beta/types_.rst b/packages/google-cloud-ces/docs/ces_v1beta/types_.rst new file mode 100644 index 000000000000..ed10f5da5b4c --- /dev/null +++ b/packages/google-cloud-ces/docs/ces_v1beta/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Ces v1beta API +===================================== + +.. automodule:: google.cloud.ces_v1beta.types + :members: + :show-inheritance: diff --git a/packages/google-cloud-ces/docs/ces_v1beta/widget_service.rst b/packages/google-cloud-ces/docs/ces_v1beta/widget_service.rst new file mode 100644 index 000000000000..0c768f3ac919 --- /dev/null +++ b/packages/google-cloud-ces/docs/ces_v1beta/widget_service.rst @@ -0,0 +1,6 @@ +WidgetService +------------------------------- + +.. automodule:: google.cloud.ces_v1beta.services.widget_service + :members: + :inherited-members: diff --git a/packages/google-cloud-ces/docs/index.rst b/packages/google-cloud-ces/docs/index.rst index ea502c2dde3b..0f317b9fed3e 100644 --- a/packages/google-cloud-ces/docs/index.rst +++ b/packages/google-cloud-ces/docs/index.rst @@ -2,6 +2,9 @@ .. include:: multiprocessing.rst +This package includes clients for multiple versions of Gemini Enterprise for Customer Experience API. +By default, you will get version ``ces_v1``. + API Reference ------------- @@ -11,6 +14,14 @@ API Reference ces_v1/services_ ces_v1/types_ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + ces_v1beta/services_ + ces_v1beta/types_ + Changelog --------- diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/__init__.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/__init__.py new file mode 100644 index 000000000000..eed57c9759e7 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/__init__.py @@ -0,0 +1,615 @@ +# -*- coding: utf-8 -*- +# 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. +# +import sys + +import google.api_core as api_core + +from google.cloud.ces_v1beta import gapic_version as package_version + +__version__ = package_version.__version__ + +if sys.version_info >= (3, 8): # pragma: NO COVER + from importlib import metadata +else: # pragma: NO COVER + # TODO(https://github.com/googleapis/python-api-core/issues/835): Remove + # this code path once we drop support for Python 3.7 + import importlib_metadata as metadata + + +from .services.agent_service import AgentServiceAsyncClient, AgentServiceClient +from .services.evaluation_service import ( + EvaluationServiceAsyncClient, + EvaluationServiceClient, +) +from .services.session_service import SessionServiceAsyncClient, SessionServiceClient +from .services.tool_service import ToolServiceAsyncClient, ToolServiceClient +from .services.widget_service import WidgetServiceAsyncClient, WidgetServiceClient +from .types.agent import Agent +from .types.agent_service import ( + BatchDeleteConversationsRequest, + BatchDeleteConversationsResponse, + CreateAgentRequest, + CreateAppRequest, + CreateAppVersionRequest, + CreateDeploymentRequest, + CreateExampleRequest, + CreateGuardrailRequest, + CreateToolRequest, + CreateToolsetRequest, + DeleteAgentRequest, + DeleteAppRequest, + DeleteAppVersionRequest, + DeleteConversationRequest, + DeleteDeploymentRequest, + DeleteExampleRequest, + DeleteGuardrailRequest, + DeleteToolRequest, + DeleteToolsetRequest, + ExportAppRequest, + ExportAppResponse, + GenerateAppResourceResponse, + GetAgentRequest, + GetAppRequest, + GetAppVersionRequest, + GetChangelogRequest, + GetConversationRequest, + GetDeploymentRequest, + GetExampleRequest, + GetGuardrailRequest, + GetToolRequest, + GetToolsetRequest, + ImportAppRequest, + ImportAppResponse, + ListAgentsRequest, + ListAgentsResponse, + ListAppsRequest, + ListAppsResponse, + ListAppVersionsRequest, + ListAppVersionsResponse, + ListChangelogsRequest, + ListChangelogsResponse, + ListConversationsRequest, + ListConversationsResponse, + ListDeploymentsRequest, + ListDeploymentsResponse, + ListExamplesRequest, + ListExamplesResponse, + ListGuardrailsRequest, + ListGuardrailsResponse, + ListToolsetsRequest, + ListToolsetsResponse, + ListToolsRequest, + ListToolsResponse, + OperationMetadata, + RestoreAppVersionRequest, + RestoreAppVersionResponse, + UpdateAgentRequest, + UpdateAppRequest, + UpdateDeploymentRequest, + UpdateExampleRequest, + UpdateGuardrailRequest, + UpdateToolRequest, + UpdateToolsetRequest, +) +from .types.agent_transfers import ( + ExpressionCondition, + PythonCodeCondition, + TransferRule, +) +from .types.app import ( + AmbientSoundConfig, + App, + AudioProcessingConfig, + AudioRecordingConfig, + BargeInConfig, + ClientCertificateSettings, + CloudLoggingSettings, + ConversationLoggingSettings, + DataStoreSettings, + ErrorHandlingSettings, + EvaluationMetricsThresholds, + EvaluationPersona, + EvaluationSettings, + LanguageSettings, + LoggingSettings, + MetricAnalysisSettings, + RedactionConfig, + SynthesizeSpeechConfig, + TimeZoneSettings, +) +from .types.app_version import AppSnapshot, AppVersion +from .types.auth import ( + ApiAuthentication, + ApiKeyConfig, + BearerTokenConfig, + EndUserAuthConfig, + OAuthConfig, + ServiceAccountAuthConfig, + ServiceAgentIdTokenAuthConfig, +) +from .types.bigquery_export import BigQueryExportSettings +from .types.changelog import Changelog +from .types.client_function import ClientFunction +from .types.common import ( + Callback, + ChannelProfile, + ExecutionType, + ModelSettings, + ServiceDirectoryConfig, + Span, + TlsConfig, + TriggerAction, +) +from .types.connector_tool import Action, ConnectorTool +from .types.connector_toolset import ConnectorToolset +from .types.conversation import Conversation +from .types.data_store import DataStore +from .types.data_store_tool import DataStoreTool +from .types.deployment import Deployment +from .types.evaluation import ( + AggregatedMetrics, + Evaluation, + EvaluationConfig, + EvaluationDataset, + EvaluationErrorInfo, + EvaluationExpectation, + EvaluationResult, + EvaluationRun, + LatencyReport, + OptimizationConfig, + PersonaRunConfig, + RunEvaluationRequest, + ScheduledEvaluationRun, +) +from .types.evaluation_service import ( + CreateEvaluationDatasetRequest, + CreateEvaluationExpectationRequest, + CreateEvaluationRequest, + CreateScheduledEvaluationRunRequest, + DeleteEvaluationDatasetRequest, + DeleteEvaluationExpectationRequest, + DeleteEvaluationRequest, + DeleteEvaluationResultRequest, + DeleteEvaluationRunOperationMetadata, + DeleteEvaluationRunRequest, + DeleteScheduledEvaluationRunRequest, + GenerateEvaluationOperationMetadata, + GenerateEvaluationRequest, + GetEvaluationDatasetRequest, + GetEvaluationExpectationRequest, + GetEvaluationRequest, + GetEvaluationResultRequest, + GetEvaluationRunRequest, + GetScheduledEvaluationRunRequest, + ImportEvaluationsOperationMetadata, + ImportEvaluationsRequest, + ImportEvaluationsResponse, + ListEvaluationDatasetsRequest, + ListEvaluationDatasetsResponse, + ListEvaluationExpectationsRequest, + ListEvaluationExpectationsResponse, + ListEvaluationResultsRequest, + ListEvaluationResultsResponse, + ListEvaluationRunsRequest, + ListEvaluationRunsResponse, + ListEvaluationsRequest, + ListEvaluationsResponse, + ListScheduledEvaluationRunsRequest, + ListScheduledEvaluationRunsResponse, + RunEvaluationOperationMetadata, + RunEvaluationResponse, + TestPersonaVoiceRequest, + TestPersonaVoiceResponse, + UpdateEvaluationDatasetRequest, + UpdateEvaluationExpectationRequest, + UpdateEvaluationRequest, + UpdateScheduledEvaluationRunRequest, + UploadEvaluationAudioRequest, + UploadEvaluationAudioResponse, +) +from .types.example import ( + AgentTransfer, + Blob, + Chunk, + Example, + Image, + Message, + ToolCall, + ToolResponse, +) +from .types.fakes import CodeBlock, EvaluationToolCallBehaviour, ToolFakeConfig +from .types.file_search_tool import FileSearchTool +from .types.golden_run import GoldenRunMethod +from .types.google_search_tool import GoogleSearchTool +from .types.guardrail import Guardrail +from .types.mcp_tool import McpTool +from .types.mcp_toolset import McpToolset +from .types.omnichannel import Omnichannel, OmnichannelIntegrationConfig +from .types.omnichannel_service import OmnichannelOperationMetadata +from .types.open_api_tool import OpenApiTool +from .types.open_api_toolset import OpenApiToolset +from .types.python_function import PythonFunction +from .types.schema import Schema +from .types.search_suggestions import GoogleSearchSuggestions, WebSearchQuery +from .types.session_service import ( + AudioEncoding, + BidiSessionClientMessage, + BidiSessionServerMessage, + Citations, + EndSession, + Event, + GoAway, + InputAudioConfig, + InterruptionSignal, + OutputAudioConfig, + RecognitionResult, + RunSessionRequest, + RunSessionResponse, + SessionConfig, + SessionInput, + SessionOutput, + ToolCalls, + ToolResponses, +) +from .types.system_tool import SystemTool +from .types.tool import Tool +from .types.tool_service import ( + ExecuteToolRequest, + ExecuteToolResponse, + RetrieveToolSchemaRequest, + RetrieveToolSchemaResponse, + RetrieveToolsRequest, + RetrieveToolsResponse, +) +from .types.toolset import Toolset +from .types.toolset_tool import ToolsetTool +from .types.widget_service import GenerateChatTokenRequest, GenerateChatTokenResponse +from .types.widget_tool import WidgetTool + +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.cloud.ces_v1beta") # type: ignore + api_core.check_dependency_versions("google.cloud.ces_v1beta") # type: ignore +else: # pragma: NO COVER + # An older version of api_core is installed which does not define the + # functions above. We do equivalent checks manually. + try: + import sys + import warnings + + _py_version_str = sys.version.split()[0] + _package_label = "google.cloud.ces_v1beta" + if sys.version_info < (3, 9): + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.9, and then update {_package_label}.", + FutureWarning, + ) + if sys.version_info[:2] == (3, 9): + warnings.warn( + f"You are using a Python version ({_py_version_str}) " + + f"which Google will stop supporting in {_package_label} in " + + "January 2026. Please " + + "upgrade to the latest Python version, or at " + + "least to Python 3.10, before then, and " + + f"then update {_package_label}.", + FutureWarning, + ) + + def parse_version_to_tuple(version_string: str): + """Safely converts a semantic version string to a comparable tuple of integers. + Example: "4.25.8" -> (4, 25, 8) + Ignores non-numeric parts and handles common version formats. + Args: + version_string: Version string in the format "x.y.z" or "x.y.z" + Returns: + Tuple of integers for the parsed version string. + """ + parts = [] + for part in version_string.split("."): + try: + parts.append(int(part)) + except ValueError: + # If it's a non-numeric part (e.g., '1.0.0b1' -> 'b1'), stop here. + # This is a simplification compared to 'packaging.parse_version', but sufficient + # for comparing strictly numeric semantic versions. + break + return tuple(parts) + + def _get_version(dependency_name): + try: + version_string: str = metadata.version(dependency_name) + parsed_version = parse_version_to_tuple(version_string) + return (parsed_version, version_string) + except Exception: + # Catch exceptions from metadata.version() (e.g., PackageNotFoundError) + # or errors during parse_version_to_tuple + return (None, "--") + + _dependency_package = "google.protobuf" + _next_supported_version = "4.25.8" + _next_supported_version_tuple = (4, 25, 8) + _recommendation = " (we recommend 6.x)" + (_version_used, _version_used_string) = _get_version(_dependency_package) + if _version_used and _version_used < _next_supported_version_tuple: + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) + except Exception: + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) + +__all__ = ( + "AgentServiceAsyncClient", + "EvaluationServiceAsyncClient", + "SessionServiceAsyncClient", + "ToolServiceAsyncClient", + "WidgetServiceAsyncClient", + "Action", + "Agent", + "AgentServiceClient", + "AgentTransfer", + "AggregatedMetrics", + "AmbientSoundConfig", + "ApiAuthentication", + "ApiKeyConfig", + "App", + "AppSnapshot", + "AppVersion", + "AudioEncoding", + "AudioProcessingConfig", + "AudioRecordingConfig", + "BargeInConfig", + "BatchDeleteConversationsRequest", + "BatchDeleteConversationsResponse", + "BearerTokenConfig", + "BidiSessionClientMessage", + "BidiSessionServerMessage", + "BigQueryExportSettings", + "Blob", + "Callback", + "Changelog", + "ChannelProfile", + "Chunk", + "Citations", + "ClientCertificateSettings", + "ClientFunction", + "CloudLoggingSettings", + "CodeBlock", + "ConnectorTool", + "ConnectorToolset", + "Conversation", + "ConversationLoggingSettings", + "CreateAgentRequest", + "CreateAppRequest", + "CreateAppVersionRequest", + "CreateDeploymentRequest", + "CreateEvaluationDatasetRequest", + "CreateEvaluationExpectationRequest", + "CreateEvaluationRequest", + "CreateExampleRequest", + "CreateGuardrailRequest", + "CreateScheduledEvaluationRunRequest", + "CreateToolRequest", + "CreateToolsetRequest", + "DataStore", + "DataStoreSettings", + "DataStoreTool", + "DeleteAgentRequest", + "DeleteAppRequest", + "DeleteAppVersionRequest", + "DeleteConversationRequest", + "DeleteDeploymentRequest", + "DeleteEvaluationDatasetRequest", + "DeleteEvaluationExpectationRequest", + "DeleteEvaluationRequest", + "DeleteEvaluationResultRequest", + "DeleteEvaluationRunOperationMetadata", + "DeleteEvaluationRunRequest", + "DeleteExampleRequest", + "DeleteGuardrailRequest", + "DeleteScheduledEvaluationRunRequest", + "DeleteToolRequest", + "DeleteToolsetRequest", + "Deployment", + "EndSession", + "EndUserAuthConfig", + "ErrorHandlingSettings", + "Evaluation", + "EvaluationConfig", + "EvaluationDataset", + "EvaluationErrorInfo", + "EvaluationExpectation", + "EvaluationMetricsThresholds", + "EvaluationPersona", + "EvaluationResult", + "EvaluationRun", + "EvaluationServiceClient", + "EvaluationSettings", + "EvaluationToolCallBehaviour", + "Event", + "Example", + "ExecuteToolRequest", + "ExecuteToolResponse", + "ExecutionType", + "ExportAppRequest", + "ExportAppResponse", + "ExpressionCondition", + "FileSearchTool", + "GenerateAppResourceResponse", + "GenerateChatTokenRequest", + "GenerateChatTokenResponse", + "GenerateEvaluationOperationMetadata", + "GenerateEvaluationRequest", + "GetAgentRequest", + "GetAppRequest", + "GetAppVersionRequest", + "GetChangelogRequest", + "GetConversationRequest", + "GetDeploymentRequest", + "GetEvaluationDatasetRequest", + "GetEvaluationExpectationRequest", + "GetEvaluationRequest", + "GetEvaluationResultRequest", + "GetEvaluationRunRequest", + "GetExampleRequest", + "GetGuardrailRequest", + "GetScheduledEvaluationRunRequest", + "GetToolRequest", + "GetToolsetRequest", + "GoAway", + "GoldenRunMethod", + "GoogleSearchSuggestions", + "GoogleSearchTool", + "Guardrail", + "Image", + "ImportAppRequest", + "ImportAppResponse", + "ImportEvaluationsOperationMetadata", + "ImportEvaluationsRequest", + "ImportEvaluationsResponse", + "InputAudioConfig", + "InterruptionSignal", + "LanguageSettings", + "LatencyReport", + "ListAgentsRequest", + "ListAgentsResponse", + "ListAppVersionsRequest", + "ListAppVersionsResponse", + "ListAppsRequest", + "ListAppsResponse", + "ListChangelogsRequest", + "ListChangelogsResponse", + "ListConversationsRequest", + "ListConversationsResponse", + "ListDeploymentsRequest", + "ListDeploymentsResponse", + "ListEvaluationDatasetsRequest", + "ListEvaluationDatasetsResponse", + "ListEvaluationExpectationsRequest", + "ListEvaluationExpectationsResponse", + "ListEvaluationResultsRequest", + "ListEvaluationResultsResponse", + "ListEvaluationRunsRequest", + "ListEvaluationRunsResponse", + "ListEvaluationsRequest", + "ListEvaluationsResponse", + "ListExamplesRequest", + "ListExamplesResponse", + "ListGuardrailsRequest", + "ListGuardrailsResponse", + "ListScheduledEvaluationRunsRequest", + "ListScheduledEvaluationRunsResponse", + "ListToolsRequest", + "ListToolsResponse", + "ListToolsetsRequest", + "ListToolsetsResponse", + "LoggingSettings", + "McpTool", + "McpToolset", + "Message", + "MetricAnalysisSettings", + "ModelSettings", + "OAuthConfig", + "Omnichannel", + "OmnichannelIntegrationConfig", + "OmnichannelOperationMetadata", + "OpenApiTool", + "OpenApiToolset", + "OperationMetadata", + "OptimizationConfig", + "OutputAudioConfig", + "PersonaRunConfig", + "PythonCodeCondition", + "PythonFunction", + "RecognitionResult", + "RedactionConfig", + "RestoreAppVersionRequest", + "RestoreAppVersionResponse", + "RetrieveToolSchemaRequest", + "RetrieveToolSchemaResponse", + "RetrieveToolsRequest", + "RetrieveToolsResponse", + "RunEvaluationOperationMetadata", + "RunEvaluationRequest", + "RunEvaluationResponse", + "RunSessionRequest", + "RunSessionResponse", + "ScheduledEvaluationRun", + "Schema", + "ServiceAccountAuthConfig", + "ServiceAgentIdTokenAuthConfig", + "ServiceDirectoryConfig", + "SessionConfig", + "SessionInput", + "SessionOutput", + "SessionServiceClient", + "Span", + "SynthesizeSpeechConfig", + "SystemTool", + "TestPersonaVoiceRequest", + "TestPersonaVoiceResponse", + "TimeZoneSettings", + "TlsConfig", + "Tool", + "ToolCall", + "ToolCalls", + "ToolFakeConfig", + "ToolResponse", + "ToolResponses", + "ToolServiceClient", + "Toolset", + "ToolsetTool", + "TransferRule", + "TriggerAction", + "UpdateAgentRequest", + "UpdateAppRequest", + "UpdateDeploymentRequest", + "UpdateEvaluationDatasetRequest", + "UpdateEvaluationExpectationRequest", + "UpdateEvaluationRequest", + "UpdateExampleRequest", + "UpdateGuardrailRequest", + "UpdateScheduledEvaluationRunRequest", + "UpdateToolRequest", + "UpdateToolsetRequest", + "UploadEvaluationAudioRequest", + "UploadEvaluationAudioResponse", + "WebSearchQuery", + "WidgetServiceClient", + "WidgetTool", +) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/gapic_metadata.json b/packages/google-cloud-ces/google/cloud/ces_v1beta/gapic_metadata.json new file mode 100644 index 000000000000..41bc6f259df8 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/gapic_metadata.json @@ -0,0 +1,1379 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.ces_v1beta", + "protoPackage": "google.cloud.ces.v1beta", + "schema": "1.0", + "services": { + "AgentService": { + "clients": { + "grpc": { + "libraryClient": "AgentServiceClient", + "rpcs": { + "BatchDeleteConversations": { + "methods": [ + "batch_delete_conversations" + ] + }, + "CreateAgent": { + "methods": [ + "create_agent" + ] + }, + "CreateApp": { + "methods": [ + "create_app" + ] + }, + "CreateAppVersion": { + "methods": [ + "create_app_version" + ] + }, + "CreateDeployment": { + "methods": [ + "create_deployment" + ] + }, + "CreateExample": { + "methods": [ + "create_example" + ] + }, + "CreateGuardrail": { + "methods": [ + "create_guardrail" + ] + }, + "CreateTool": { + "methods": [ + "create_tool" + ] + }, + "CreateToolset": { + "methods": [ + "create_toolset" + ] + }, + "DeleteAgent": { + "methods": [ + "delete_agent" + ] + }, + "DeleteApp": { + "methods": [ + "delete_app" + ] + }, + "DeleteAppVersion": { + "methods": [ + "delete_app_version" + ] + }, + "DeleteConversation": { + "methods": [ + "delete_conversation" + ] + }, + "DeleteDeployment": { + "methods": [ + "delete_deployment" + ] + }, + "DeleteExample": { + "methods": [ + "delete_example" + ] + }, + "DeleteGuardrail": { + "methods": [ + "delete_guardrail" + ] + }, + "DeleteTool": { + "methods": [ + "delete_tool" + ] + }, + "DeleteToolset": { + "methods": [ + "delete_toolset" + ] + }, + "ExportApp": { + "methods": [ + "export_app" + ] + }, + "GetAgent": { + "methods": [ + "get_agent" + ] + }, + "GetApp": { + "methods": [ + "get_app" + ] + }, + "GetAppVersion": { + "methods": [ + "get_app_version" + ] + }, + "GetChangelog": { + "methods": [ + "get_changelog" + ] + }, + "GetConversation": { + "methods": [ + "get_conversation" + ] + }, + "GetDeployment": { + "methods": [ + "get_deployment" + ] + }, + "GetExample": { + "methods": [ + "get_example" + ] + }, + "GetGuardrail": { + "methods": [ + "get_guardrail" + ] + }, + "GetTool": { + "methods": [ + "get_tool" + ] + }, + "GetToolset": { + "methods": [ + "get_toolset" + ] + }, + "ImportApp": { + "methods": [ + "import_app" + ] + }, + "ListAgents": { + "methods": [ + "list_agents" + ] + }, + "ListAppVersions": { + "methods": [ + "list_app_versions" + ] + }, + "ListApps": { + "methods": [ + "list_apps" + ] + }, + "ListChangelogs": { + "methods": [ + "list_changelogs" + ] + }, + "ListConversations": { + "methods": [ + "list_conversations" + ] + }, + "ListDeployments": { + "methods": [ + "list_deployments" + ] + }, + "ListExamples": { + "methods": [ + "list_examples" + ] + }, + "ListGuardrails": { + "methods": [ + "list_guardrails" + ] + }, + "ListTools": { + "methods": [ + "list_tools" + ] + }, + "ListToolsets": { + "methods": [ + "list_toolsets" + ] + }, + "RestoreAppVersion": { + "methods": [ + "restore_app_version" + ] + }, + "UpdateAgent": { + "methods": [ + "update_agent" + ] + }, + "UpdateApp": { + "methods": [ + "update_app" + ] + }, + "UpdateDeployment": { + "methods": [ + "update_deployment" + ] + }, + "UpdateExample": { + "methods": [ + "update_example" + ] + }, + "UpdateGuardrail": { + "methods": [ + "update_guardrail" + ] + }, + "UpdateTool": { + "methods": [ + "update_tool" + ] + }, + "UpdateToolset": { + "methods": [ + "update_toolset" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AgentServiceAsyncClient", + "rpcs": { + "BatchDeleteConversations": { + "methods": [ + "batch_delete_conversations" + ] + }, + "CreateAgent": { + "methods": [ + "create_agent" + ] + }, + "CreateApp": { + "methods": [ + "create_app" + ] + }, + "CreateAppVersion": { + "methods": [ + "create_app_version" + ] + }, + "CreateDeployment": { + "methods": [ + "create_deployment" + ] + }, + "CreateExample": { + "methods": [ + "create_example" + ] + }, + "CreateGuardrail": { + "methods": [ + "create_guardrail" + ] + }, + "CreateTool": { + "methods": [ + "create_tool" + ] + }, + "CreateToolset": { + "methods": [ + "create_toolset" + ] + }, + "DeleteAgent": { + "methods": [ + "delete_agent" + ] + }, + "DeleteApp": { + "methods": [ + "delete_app" + ] + }, + "DeleteAppVersion": { + "methods": [ + "delete_app_version" + ] + }, + "DeleteConversation": { + "methods": [ + "delete_conversation" + ] + }, + "DeleteDeployment": { + "methods": [ + "delete_deployment" + ] + }, + "DeleteExample": { + "methods": [ + "delete_example" + ] + }, + "DeleteGuardrail": { + "methods": [ + "delete_guardrail" + ] + }, + "DeleteTool": { + "methods": [ + "delete_tool" + ] + }, + "DeleteToolset": { + "methods": [ + "delete_toolset" + ] + }, + "ExportApp": { + "methods": [ + "export_app" + ] + }, + "GetAgent": { + "methods": [ + "get_agent" + ] + }, + "GetApp": { + "methods": [ + "get_app" + ] + }, + "GetAppVersion": { + "methods": [ + "get_app_version" + ] + }, + "GetChangelog": { + "methods": [ + "get_changelog" + ] + }, + "GetConversation": { + "methods": [ + "get_conversation" + ] + }, + "GetDeployment": { + "methods": [ + "get_deployment" + ] + }, + "GetExample": { + "methods": [ + "get_example" + ] + }, + "GetGuardrail": { + "methods": [ + "get_guardrail" + ] + }, + "GetTool": { + "methods": [ + "get_tool" + ] + }, + "GetToolset": { + "methods": [ + "get_toolset" + ] + }, + "ImportApp": { + "methods": [ + "import_app" + ] + }, + "ListAgents": { + "methods": [ + "list_agents" + ] + }, + "ListAppVersions": { + "methods": [ + "list_app_versions" + ] + }, + "ListApps": { + "methods": [ + "list_apps" + ] + }, + "ListChangelogs": { + "methods": [ + "list_changelogs" + ] + }, + "ListConversations": { + "methods": [ + "list_conversations" + ] + }, + "ListDeployments": { + "methods": [ + "list_deployments" + ] + }, + "ListExamples": { + "methods": [ + "list_examples" + ] + }, + "ListGuardrails": { + "methods": [ + "list_guardrails" + ] + }, + "ListTools": { + "methods": [ + "list_tools" + ] + }, + "ListToolsets": { + "methods": [ + "list_toolsets" + ] + }, + "RestoreAppVersion": { + "methods": [ + "restore_app_version" + ] + }, + "UpdateAgent": { + "methods": [ + "update_agent" + ] + }, + "UpdateApp": { + "methods": [ + "update_app" + ] + }, + "UpdateDeployment": { + "methods": [ + "update_deployment" + ] + }, + "UpdateExample": { + "methods": [ + "update_example" + ] + }, + "UpdateGuardrail": { + "methods": [ + "update_guardrail" + ] + }, + "UpdateTool": { + "methods": [ + "update_tool" + ] + }, + "UpdateToolset": { + "methods": [ + "update_toolset" + ] + } + } + }, + "rest": { + "libraryClient": "AgentServiceClient", + "rpcs": { + "BatchDeleteConversations": { + "methods": [ + "batch_delete_conversations" + ] + }, + "CreateAgent": { + "methods": [ + "create_agent" + ] + }, + "CreateApp": { + "methods": [ + "create_app" + ] + }, + "CreateAppVersion": { + "methods": [ + "create_app_version" + ] + }, + "CreateDeployment": { + "methods": [ + "create_deployment" + ] + }, + "CreateExample": { + "methods": [ + "create_example" + ] + }, + "CreateGuardrail": { + "methods": [ + "create_guardrail" + ] + }, + "CreateTool": { + "methods": [ + "create_tool" + ] + }, + "CreateToolset": { + "methods": [ + "create_toolset" + ] + }, + "DeleteAgent": { + "methods": [ + "delete_agent" + ] + }, + "DeleteApp": { + "methods": [ + "delete_app" + ] + }, + "DeleteAppVersion": { + "methods": [ + "delete_app_version" + ] + }, + "DeleteConversation": { + "methods": [ + "delete_conversation" + ] + }, + "DeleteDeployment": { + "methods": [ + "delete_deployment" + ] + }, + "DeleteExample": { + "methods": [ + "delete_example" + ] + }, + "DeleteGuardrail": { + "methods": [ + "delete_guardrail" + ] + }, + "DeleteTool": { + "methods": [ + "delete_tool" + ] + }, + "DeleteToolset": { + "methods": [ + "delete_toolset" + ] + }, + "ExportApp": { + "methods": [ + "export_app" + ] + }, + "GetAgent": { + "methods": [ + "get_agent" + ] + }, + "GetApp": { + "methods": [ + "get_app" + ] + }, + "GetAppVersion": { + "methods": [ + "get_app_version" + ] + }, + "GetChangelog": { + "methods": [ + "get_changelog" + ] + }, + "GetConversation": { + "methods": [ + "get_conversation" + ] + }, + "GetDeployment": { + "methods": [ + "get_deployment" + ] + }, + "GetExample": { + "methods": [ + "get_example" + ] + }, + "GetGuardrail": { + "methods": [ + "get_guardrail" + ] + }, + "GetTool": { + "methods": [ + "get_tool" + ] + }, + "GetToolset": { + "methods": [ + "get_toolset" + ] + }, + "ImportApp": { + "methods": [ + "import_app" + ] + }, + "ListAgents": { + "methods": [ + "list_agents" + ] + }, + "ListAppVersions": { + "methods": [ + "list_app_versions" + ] + }, + "ListApps": { + "methods": [ + "list_apps" + ] + }, + "ListChangelogs": { + "methods": [ + "list_changelogs" + ] + }, + "ListConversations": { + "methods": [ + "list_conversations" + ] + }, + "ListDeployments": { + "methods": [ + "list_deployments" + ] + }, + "ListExamples": { + "methods": [ + "list_examples" + ] + }, + "ListGuardrails": { + "methods": [ + "list_guardrails" + ] + }, + "ListTools": { + "methods": [ + "list_tools" + ] + }, + "ListToolsets": { + "methods": [ + "list_toolsets" + ] + }, + "RestoreAppVersion": { + "methods": [ + "restore_app_version" + ] + }, + "UpdateAgent": { + "methods": [ + "update_agent" + ] + }, + "UpdateApp": { + "methods": [ + "update_app" + ] + }, + "UpdateDeployment": { + "methods": [ + "update_deployment" + ] + }, + "UpdateExample": { + "methods": [ + "update_example" + ] + }, + "UpdateGuardrail": { + "methods": [ + "update_guardrail" + ] + }, + "UpdateTool": { + "methods": [ + "update_tool" + ] + }, + "UpdateToolset": { + "methods": [ + "update_toolset" + ] + } + } + } + } + }, + "EvaluationService": { + "clients": { + "grpc": { + "libraryClient": "EvaluationServiceClient", + "rpcs": { + "CreateEvaluation": { + "methods": [ + "create_evaluation" + ] + }, + "CreateEvaluationDataset": { + "methods": [ + "create_evaluation_dataset" + ] + }, + "CreateEvaluationExpectation": { + "methods": [ + "create_evaluation_expectation" + ] + }, + "CreateScheduledEvaluationRun": { + "methods": [ + "create_scheduled_evaluation_run" + ] + }, + "DeleteEvaluation": { + "methods": [ + "delete_evaluation" + ] + }, + "DeleteEvaluationDataset": { + "methods": [ + "delete_evaluation_dataset" + ] + }, + "DeleteEvaluationExpectation": { + "methods": [ + "delete_evaluation_expectation" + ] + }, + "DeleteEvaluationResult": { + "methods": [ + "delete_evaluation_result" + ] + }, + "DeleteEvaluationRun": { + "methods": [ + "delete_evaluation_run" + ] + }, + "DeleteScheduledEvaluationRun": { + "methods": [ + "delete_scheduled_evaluation_run" + ] + }, + "GenerateEvaluation": { + "methods": [ + "generate_evaluation" + ] + }, + "GetEvaluation": { + "methods": [ + "get_evaluation" + ] + }, + "GetEvaluationDataset": { + "methods": [ + "get_evaluation_dataset" + ] + }, + "GetEvaluationExpectation": { + "methods": [ + "get_evaluation_expectation" + ] + }, + "GetEvaluationResult": { + "methods": [ + "get_evaluation_result" + ] + }, + "GetEvaluationRun": { + "methods": [ + "get_evaluation_run" + ] + }, + "GetScheduledEvaluationRun": { + "methods": [ + "get_scheduled_evaluation_run" + ] + }, + "ImportEvaluations": { + "methods": [ + "import_evaluations" + ] + }, + "ListEvaluationDatasets": { + "methods": [ + "list_evaluation_datasets" + ] + }, + "ListEvaluationExpectations": { + "methods": [ + "list_evaluation_expectations" + ] + }, + "ListEvaluationResults": { + "methods": [ + "list_evaluation_results" + ] + }, + "ListEvaluationRuns": { + "methods": [ + "list_evaluation_runs" + ] + }, + "ListEvaluations": { + "methods": [ + "list_evaluations" + ] + }, + "ListScheduledEvaluationRuns": { + "methods": [ + "list_scheduled_evaluation_runs" + ] + }, + "RunEvaluation": { + "methods": [ + "run_evaluation" + ] + }, + "TestPersonaVoice": { + "methods": [ + "test_persona_voice" + ] + }, + "UpdateEvaluation": { + "methods": [ + "update_evaluation" + ] + }, + "UpdateEvaluationDataset": { + "methods": [ + "update_evaluation_dataset" + ] + }, + "UpdateEvaluationExpectation": { + "methods": [ + "update_evaluation_expectation" + ] + }, + "UpdateScheduledEvaluationRun": { + "methods": [ + "update_scheduled_evaluation_run" + ] + }, + "UploadEvaluationAudio": { + "methods": [ + "upload_evaluation_audio" + ] + } + } + }, + "grpc-async": { + "libraryClient": "EvaluationServiceAsyncClient", + "rpcs": { + "CreateEvaluation": { + "methods": [ + "create_evaluation" + ] + }, + "CreateEvaluationDataset": { + "methods": [ + "create_evaluation_dataset" + ] + }, + "CreateEvaluationExpectation": { + "methods": [ + "create_evaluation_expectation" + ] + }, + "CreateScheduledEvaluationRun": { + "methods": [ + "create_scheduled_evaluation_run" + ] + }, + "DeleteEvaluation": { + "methods": [ + "delete_evaluation" + ] + }, + "DeleteEvaluationDataset": { + "methods": [ + "delete_evaluation_dataset" + ] + }, + "DeleteEvaluationExpectation": { + "methods": [ + "delete_evaluation_expectation" + ] + }, + "DeleteEvaluationResult": { + "methods": [ + "delete_evaluation_result" + ] + }, + "DeleteEvaluationRun": { + "methods": [ + "delete_evaluation_run" + ] + }, + "DeleteScheduledEvaluationRun": { + "methods": [ + "delete_scheduled_evaluation_run" + ] + }, + "GenerateEvaluation": { + "methods": [ + "generate_evaluation" + ] + }, + "GetEvaluation": { + "methods": [ + "get_evaluation" + ] + }, + "GetEvaluationDataset": { + "methods": [ + "get_evaluation_dataset" + ] + }, + "GetEvaluationExpectation": { + "methods": [ + "get_evaluation_expectation" + ] + }, + "GetEvaluationResult": { + "methods": [ + "get_evaluation_result" + ] + }, + "GetEvaluationRun": { + "methods": [ + "get_evaluation_run" + ] + }, + "GetScheduledEvaluationRun": { + "methods": [ + "get_scheduled_evaluation_run" + ] + }, + "ImportEvaluations": { + "methods": [ + "import_evaluations" + ] + }, + "ListEvaluationDatasets": { + "methods": [ + "list_evaluation_datasets" + ] + }, + "ListEvaluationExpectations": { + "methods": [ + "list_evaluation_expectations" + ] + }, + "ListEvaluationResults": { + "methods": [ + "list_evaluation_results" + ] + }, + "ListEvaluationRuns": { + "methods": [ + "list_evaluation_runs" + ] + }, + "ListEvaluations": { + "methods": [ + "list_evaluations" + ] + }, + "ListScheduledEvaluationRuns": { + "methods": [ + "list_scheduled_evaluation_runs" + ] + }, + "RunEvaluation": { + "methods": [ + "run_evaluation" + ] + }, + "TestPersonaVoice": { + "methods": [ + "test_persona_voice" + ] + }, + "UpdateEvaluation": { + "methods": [ + "update_evaluation" + ] + }, + "UpdateEvaluationDataset": { + "methods": [ + "update_evaluation_dataset" + ] + }, + "UpdateEvaluationExpectation": { + "methods": [ + "update_evaluation_expectation" + ] + }, + "UpdateScheduledEvaluationRun": { + "methods": [ + "update_scheduled_evaluation_run" + ] + }, + "UploadEvaluationAudio": { + "methods": [ + "upload_evaluation_audio" + ] + } + } + }, + "rest": { + "libraryClient": "EvaluationServiceClient", + "rpcs": { + "CreateEvaluation": { + "methods": [ + "create_evaluation" + ] + }, + "CreateEvaluationDataset": { + "methods": [ + "create_evaluation_dataset" + ] + }, + "CreateEvaluationExpectation": { + "methods": [ + "create_evaluation_expectation" + ] + }, + "CreateScheduledEvaluationRun": { + "methods": [ + "create_scheduled_evaluation_run" + ] + }, + "DeleteEvaluation": { + "methods": [ + "delete_evaluation" + ] + }, + "DeleteEvaluationDataset": { + "methods": [ + "delete_evaluation_dataset" + ] + }, + "DeleteEvaluationExpectation": { + "methods": [ + "delete_evaluation_expectation" + ] + }, + "DeleteEvaluationResult": { + "methods": [ + "delete_evaluation_result" + ] + }, + "DeleteEvaluationRun": { + "methods": [ + "delete_evaluation_run" + ] + }, + "DeleteScheduledEvaluationRun": { + "methods": [ + "delete_scheduled_evaluation_run" + ] + }, + "GenerateEvaluation": { + "methods": [ + "generate_evaluation" + ] + }, + "GetEvaluation": { + "methods": [ + "get_evaluation" + ] + }, + "GetEvaluationDataset": { + "methods": [ + "get_evaluation_dataset" + ] + }, + "GetEvaluationExpectation": { + "methods": [ + "get_evaluation_expectation" + ] + }, + "GetEvaluationResult": { + "methods": [ + "get_evaluation_result" + ] + }, + "GetEvaluationRun": { + "methods": [ + "get_evaluation_run" + ] + }, + "GetScheduledEvaluationRun": { + "methods": [ + "get_scheduled_evaluation_run" + ] + }, + "ImportEvaluations": { + "methods": [ + "import_evaluations" + ] + }, + "ListEvaluationDatasets": { + "methods": [ + "list_evaluation_datasets" + ] + }, + "ListEvaluationExpectations": { + "methods": [ + "list_evaluation_expectations" + ] + }, + "ListEvaluationResults": { + "methods": [ + "list_evaluation_results" + ] + }, + "ListEvaluationRuns": { + "methods": [ + "list_evaluation_runs" + ] + }, + "ListEvaluations": { + "methods": [ + "list_evaluations" + ] + }, + "ListScheduledEvaluationRuns": { + "methods": [ + "list_scheduled_evaluation_runs" + ] + }, + "RunEvaluation": { + "methods": [ + "run_evaluation" + ] + }, + "TestPersonaVoice": { + "methods": [ + "test_persona_voice" + ] + }, + "UpdateEvaluation": { + "methods": [ + "update_evaluation" + ] + }, + "UpdateEvaluationDataset": { + "methods": [ + "update_evaluation_dataset" + ] + }, + "UpdateEvaluationExpectation": { + "methods": [ + "update_evaluation_expectation" + ] + }, + "UpdateScheduledEvaluationRun": { + "methods": [ + "update_scheduled_evaluation_run" + ] + }, + "UploadEvaluationAudio": { + "methods": [ + "upload_evaluation_audio" + ] + } + } + } + } + }, + "SessionService": { + "clients": { + "grpc": { + "libraryClient": "SessionServiceClient", + "rpcs": { + "BidiRunSession": { + "methods": [ + "bidi_run_session" + ] + }, + "RunSession": { + "methods": [ + "run_session" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SessionServiceAsyncClient", + "rpcs": { + "BidiRunSession": { + "methods": [ + "bidi_run_session" + ] + }, + "RunSession": { + "methods": [ + "run_session" + ] + } + } + }, + "rest": { + "libraryClient": "SessionServiceClient", + "rpcs": { + "BidiRunSession": { + "methods": [ + "bidi_run_session" + ] + }, + "RunSession": { + "methods": [ + "run_session" + ] + } + } + } + } + }, + "ToolService": { + "clients": { + "grpc": { + "libraryClient": "ToolServiceClient", + "rpcs": { + "ExecuteTool": { + "methods": [ + "execute_tool" + ] + }, + "RetrieveToolSchema": { + "methods": [ + "retrieve_tool_schema" + ] + }, + "RetrieveTools": { + "methods": [ + "retrieve_tools" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ToolServiceAsyncClient", + "rpcs": { + "ExecuteTool": { + "methods": [ + "execute_tool" + ] + }, + "RetrieveToolSchema": { + "methods": [ + "retrieve_tool_schema" + ] + }, + "RetrieveTools": { + "methods": [ + "retrieve_tools" + ] + } + } + }, + "rest": { + "libraryClient": "ToolServiceClient", + "rpcs": { + "ExecuteTool": { + "methods": [ + "execute_tool" + ] + }, + "RetrieveToolSchema": { + "methods": [ + "retrieve_tool_schema" + ] + }, + "RetrieveTools": { + "methods": [ + "retrieve_tools" + ] + } + } + } + } + }, + "WidgetService": { + "clients": { + "grpc": { + "libraryClient": "WidgetServiceClient", + "rpcs": { + "GenerateChatToken": { + "methods": [ + "generate_chat_token" + ] + } + } + }, + "grpc-async": { + "libraryClient": "WidgetServiceAsyncClient", + "rpcs": { + "GenerateChatToken": { + "methods": [ + "generate_chat_token" + ] + } + } + }, + "rest": { + "libraryClient": "WidgetServiceClient", + "rpcs": { + "GenerateChatToken": { + "methods": [ + "generate_chat_token" + ] + } + } + } + } + } + } +} diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/gapic_version.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/gapic_version.py new file mode 100644 index 000000000000..20a9cd975b02 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# 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. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/py.typed b/packages/google-cloud-ces/google/cloud/ces_v1beta/py.typed new file mode 100644 index 000000000000..b5ef88a99288 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-ces package uses inline types. diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/__init__.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/__init__.py new file mode 100644 index 000000000000..cbf94b283c70 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# 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. +# diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/__init__.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/__init__.py new file mode 100644 index 000000000000..447d8448cd91 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# 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 .async_client import AgentServiceAsyncClient +from .client import AgentServiceClient + +__all__ = ( + "AgentServiceClient", + "AgentServiceAsyncClient", +) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/async_client.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/async_client.py new file mode 100644 index 000000000000..4f12854f6069 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/async_client.py @@ -0,0 +1,6585 @@ +# -*- coding: utf-8 -*- +# 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. +# +import logging as std_logging +import re +from collections import OrderedDict +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.ces_v1beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.struct_pb2 as struct_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.ces_v1beta.services.agent_service import pagers +from google.cloud.ces_v1beta.types import ( + agent, + agent_service, + agent_transfers, + app, + app_version, + changelog, + client_function, + common, + connector_tool, + connector_toolset, + conversation, + data_store_tool, + deployment, + example, + fakes, + file_search_tool, + google_search_tool, + guardrail, + mcp_tool, + mcp_toolset, + open_api_tool, + open_api_toolset, + python_function, + system_tool, + tool, + toolset, + widget_tool, +) +from google.cloud.ces_v1beta.types import agent as gcc_agent +from google.cloud.ces_v1beta.types import app as gcc_app +from google.cloud.ces_v1beta.types import app_version as gcc_app_version +from google.cloud.ces_v1beta.types import deployment as gcc_deployment +from google.cloud.ces_v1beta.types import example as gcc_example +from google.cloud.ces_v1beta.types import guardrail as gcc_guardrail +from google.cloud.ces_v1beta.types import tool as gcc_tool +from google.cloud.ces_v1beta.types import toolset as gcc_toolset + +from .client import AgentServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, AgentServiceTransport +from .transports.grpc_asyncio import AgentServiceGrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class AgentServiceAsyncClient: + """The service that manages agent-related resources in Gemini + Enterprise for Customer Engagement (CES). + """ + + _client: AgentServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = AgentServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AgentServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = AgentServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = AgentServiceClient._DEFAULT_UNIVERSE + + agent_path = staticmethod(AgentServiceClient.agent_path) + parse_agent_path = staticmethod(AgentServiceClient.parse_agent_path) + app_path = staticmethod(AgentServiceClient.app_path) + parse_app_path = staticmethod(AgentServiceClient.parse_app_path) + app_version_path = staticmethod(AgentServiceClient.app_version_path) + parse_app_version_path = staticmethod(AgentServiceClient.parse_app_version_path) + changelog_path = staticmethod(AgentServiceClient.changelog_path) + parse_changelog_path = staticmethod(AgentServiceClient.parse_changelog_path) + conversation_path = staticmethod(AgentServiceClient.conversation_path) + parse_conversation_path = staticmethod(AgentServiceClient.parse_conversation_path) + deidentify_template_path = staticmethod(AgentServiceClient.deidentify_template_path) + parse_deidentify_template_path = staticmethod( + AgentServiceClient.parse_deidentify_template_path + ) + deployment_path = staticmethod(AgentServiceClient.deployment_path) + parse_deployment_path = staticmethod(AgentServiceClient.parse_deployment_path) + dialogflow_agent_path = staticmethod(AgentServiceClient.dialogflow_agent_path) + parse_dialogflow_agent_path = staticmethod( + AgentServiceClient.parse_dialogflow_agent_path + ) + engine_path = staticmethod(AgentServiceClient.engine_path) + parse_engine_path = staticmethod(AgentServiceClient.parse_engine_path) + example_path = staticmethod(AgentServiceClient.example_path) + parse_example_path = staticmethod(AgentServiceClient.parse_example_path) + guardrail_path = staticmethod(AgentServiceClient.guardrail_path) + parse_guardrail_path = staticmethod(AgentServiceClient.parse_guardrail_path) + inspect_template_path = staticmethod(AgentServiceClient.inspect_template_path) + parse_inspect_template_path = staticmethod( + AgentServiceClient.parse_inspect_template_path + ) + secret_version_path = staticmethod(AgentServiceClient.secret_version_path) + parse_secret_version_path = staticmethod( + AgentServiceClient.parse_secret_version_path + ) + service_path = staticmethod(AgentServiceClient.service_path) + parse_service_path = staticmethod(AgentServiceClient.parse_service_path) + tool_path = staticmethod(AgentServiceClient.tool_path) + parse_tool_path = staticmethod(AgentServiceClient.parse_tool_path) + toolset_path = staticmethod(AgentServiceClient.toolset_path) + parse_toolset_path = staticmethod(AgentServiceClient.parse_toolset_path) + common_billing_account_path = staticmethod( + AgentServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + AgentServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(AgentServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(AgentServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(AgentServiceClient.common_organization_path) + parse_common_organization_path = staticmethod( + AgentServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod(AgentServiceClient.common_project_path) + parse_common_project_path = staticmethod( + AgentServiceClient.parse_common_project_path + ) + common_location_path = staticmethod(AgentServiceClient.common_location_path) + parse_common_location_path = staticmethod( + AgentServiceClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + AgentServiceAsyncClient: The constructed client. + """ + sa_info_func = ( + AgentServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(AgentServiceAsyncClient, info, *args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + AgentServiceAsyncClient: The constructed client. + """ + sa_file_func = ( + AgentServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(AgentServiceAsyncClient, filename, *args, **kwargs) + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return AgentServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> AgentServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AgentServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = AgentServiceClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, AgentServiceTransport, Callable[..., AgentServiceTransport]] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the agent service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,AgentServiceTransport,Callable[..., AgentServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the AgentServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = AgentServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.ces_v1beta.AgentServiceAsyncClient`.", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.cloud.ces.v1beta.AgentService", + "credentialsType": None, + }, + ) + + async def list_apps( + self, + request: Optional[Union[agent_service.ListAppsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAppsAsyncPager: + r"""Lists apps in the given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_list_apps(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ListAppsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_apps(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.ListAppsRequest, dict]]): + The request object. Request message for + [AgentService.ListApps][google.cloud.ces.v1beta.AgentService.ListApps]. + parent (:class:`str`): + Required. The resource name of the + location to list apps from. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.services.agent_service.pagers.ListAppsAsyncPager: + Response message for + [AgentService.ListApps][google.cloud.ces.v1beta.AgentService.ListApps]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.ListAppsRequest): + request = agent_service.ListAppsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_apps + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListAppsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_app( + self, + request: Optional[Union[agent_service.GetAppRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> app.App: + r"""Gets details of the specified app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_get_app(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.GetAppRequest( + name="name_value", + ) + + # Make the request + response = await client.get_app(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.GetAppRequest, dict]]): + The request object. Request message for + [AgentService.GetApp][google.cloud.ces.v1beta.AgentService.GetApp]. + name (:class:`str`): + Required. The resource name of the + app to retrieve. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.App: + An app serves as a top-level + container for a group of agents, + including the root agent and its + sub-agents, along with their associated + configurations. These agents work + together to achieve specific goals + within the app's context. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.GetAppRequest): + request = agent_service.GetAppRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_app] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_app( + self, + request: Optional[Union[agent_service.CreateAppRequest, dict]] = None, + *, + parent: Optional[str] = None, + app: Optional[gcc_app.App] = None, + app_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new app in the given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_create_app(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + app = ces_v1beta.App() + app.display_name = "display_name_value" + + request = ces_v1beta.CreateAppRequest( + parent="parent_value", + app=app, + ) + + # Make the request + operation = client.create_app(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.CreateAppRequest, dict]]): + The request object. Request message for + [AgentService.CreateApp][google.cloud.ces.v1beta.AgentService.CreateApp]. + parent (:class:`str`): + Required. The resource name of the + location to create an app in. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + app (:class:`google.cloud.ces_v1beta.types.App`): + Required. The app to create. + This corresponds to the ``app`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + app_id (:class:`str`): + Optional. The ID to use for the app, + which will become the final component of + the app's resource name. If not + provided, a unique ID will be + automatically assigned for the app. + + This corresponds to the ``app_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.ces_v1beta.types.App` An app serves as a top-level container for a group of agents, including the + root agent and its sub-agents, along with their + associated configurations. These agents work together + to achieve specific goals within the app's context. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, app, app_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.CreateAppRequest): + request = agent_service.CreateAppRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if app is not None: + request.app = app + if app_id is not None: + request.app_id = app_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_app + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gcc_app.App, + metadata_type=agent_service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def update_app( + self, + request: Optional[Union[agent_service.UpdateAppRequest, dict]] = None, + *, + app: Optional[gcc_app.App] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_app.App: + r"""Updates the specified app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_update_app(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + app = ces_v1beta.App() + app.display_name = "display_name_value" + + request = ces_v1beta.UpdateAppRequest( + app=app, + ) + + # Make the request + response = await client.update_app(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.UpdateAppRequest, dict]]): + The request object. Request message for + [AgentService.UpdateApp][google.cloud.ces.v1beta.AgentService.UpdateApp]. + app (:class:`google.cloud.ces_v1beta.types.App`): + Required. The app to update. + This corresponds to the ``app`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to + control which fields get updated. If the + mask is not present, all fields will be + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.App: + An app serves as a top-level + container for a group of agents, + including the root agent and its + sub-agents, along with their associated + configurations. These agents work + together to achieve specific goals + within the app's context. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [app, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.UpdateAppRequest): + request = agent_service.UpdateAppRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if app is not None: + request.app = app + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_app + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("app.name", request.app.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_app( + self, + request: Optional[Union[agent_service.DeleteAppRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes the specified app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_delete_app(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteAppRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_app(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.DeleteAppRequest, dict]]): + The request object. Request message for + [AgentService.DeleteApp][google.cloud.ces.v1beta.AgentService.DeleteApp]. + name (:class:`str`): + Required. The resource name of the + app to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.DeleteAppRequest): + request = agent_service.DeleteAppRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_app + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=agent_service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def export_app( + self, + request: Optional[Union[agent_service.ExportAppRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Exports the specified app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_export_app(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ExportAppRequest( + name="name_value", + export_format="YAML", + ) + + # Make the request + operation = client.export_app(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.ExportAppRequest, dict]]): + The request object. Request message for + [AgentService.ExportApp][google.cloud.ces.v1beta.AgentService.ExportApp]. + name (:class:`str`): + Required. The resource name of the + app to export. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.ces_v1beta.types.ExportAppResponse` Response message for + [AgentService.ExportApp][google.cloud.ces.v1beta.AgentService.ExportApp]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.ExportAppRequest): + request = agent_service.ExportAppRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.export_app + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + agent_service.ExportAppResponse, + metadata_type=agent_service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def import_app( + self, + request: Optional[Union[agent_service.ImportAppRequest, dict]] = None, + *, + parent: Optional[str] = None, + display_name: Optional[str] = None, + app_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Imports the specified app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_import_app(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ImportAppRequest( + gcs_uri="gcs_uri_value", + parent="parent_value", + ) + + # Make the request + operation = client.import_app(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.ImportAppRequest, dict]]): + The request object. Request message for + [AgentService.ImportApp][google.cloud.ces.v1beta.AgentService.ImportApp]. + parent (:class:`str`): + Required. The parent resource name + with the location of the app to import. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + display_name (:class:`str`): + Optional. The display name of the app to import. + + - If the app is created on import, and the display name + is specified, the imported app will use this display + name. If a conflict is detected with an existing app, + a timestamp will be appended to the display name to + make it unique. + - If the app is a reimport, this field should not be + set. Providing a display name during reimport will + result in an INVALID_ARGUMENT error. + + This corresponds to the ``display_name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + app_id (:class:`str`): + Optional. The ID to use for the imported app. + + - If not specified, a unique ID will be automatically + assigned for the app. + - Otherwise, the imported app will use this ID as the + final component of its resource name. If an app with + the same ID already exists at the specified location + in the project, the content of the existing app will + be replaced. + + This corresponds to the ``app_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.ces_v1beta.types.ImportAppResponse` Response message for + [AgentService.ImportApp][google.cloud.ces.v1beta.AgentService.ImportApp]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, display_name, app_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.ImportAppRequest): + request = agent_service.ImportAppRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if display_name is not None: + request.display_name = display_name + if app_id is not None: + request.app_id = app_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.import_app + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + agent_service.ImportAppResponse, + metadata_type=agent_service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_agents( + self, + request: Optional[Union[agent_service.ListAgentsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAgentsAsyncPager: + r"""Lists agents in the given app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_list_agents(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ListAgentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_agents(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.ListAgentsRequest, dict]]): + The request object. Request message for + [AgentService.ListAgents][google.cloud.ces.v1beta.AgentService.ListAgents]. + parent (:class:`str`): + Required. The resource name of the + app to list agents from. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.services.agent_service.pagers.ListAgentsAsyncPager: + Response message for + [AgentService.ListAgents][google.cloud.ces.v1beta.AgentService.ListAgents]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.ListAgentsRequest): + request = agent_service.ListAgentsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_agents + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListAgentsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_agent( + self, + request: Optional[Union[agent_service.GetAgentRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> agent.Agent: + r"""Gets details of the specified agent. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_get_agent(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.GetAgentRequest( + name="name_value", + ) + + # Make the request + response = await client.get_agent(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.GetAgentRequest, dict]]): + The request object. Request message for + [AgentService.GetAgent][google.cloud.ces.v1beta.AgentService.GetAgent]. + name (:class:`str`): + Required. The resource name of the + agent to retrieve. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Agent: + An agent acts as the fundamental + building block that provides + instructions to the Large Language Model + (LLM) for executing specific tasks. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.GetAgentRequest): + request = agent_service.GetAgentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_agent + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_agent( + self, + request: Optional[Union[agent_service.CreateAgentRequest, dict]] = None, + *, + parent: Optional[str] = None, + agent: Optional[gcc_agent.Agent] = None, + agent_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_agent.Agent: + r"""Creates a new agent in the given app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_create_agent(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + agent = ces_v1beta.Agent() + agent.display_name = "display_name_value" + + request = ces_v1beta.CreateAgentRequest( + parent="parent_value", + agent=agent, + ) + + # Make the request + response = await client.create_agent(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.CreateAgentRequest, dict]]): + The request object. Request message for + [AgentService.CreateAgent][google.cloud.ces.v1beta.AgentService.CreateAgent]. + parent (:class:`str`): + Required. The resource name of the + app to create an agent in. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + agent (:class:`google.cloud.ces_v1beta.types.Agent`): + Required. The agent to create. + This corresponds to the ``agent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + agent_id (:class:`str`): + Optional. The ID to use for the + agent, which will become the final + component of the agent's resource name. + If not provided, a unique ID will be + automatically assigned for the agent. + + This corresponds to the ``agent_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Agent: + An agent acts as the fundamental + building block that provides + instructions to the Large Language Model + (LLM) for executing specific tasks. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, agent, agent_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.CreateAgentRequest): + request = agent_service.CreateAgentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if agent is not None: + request.agent = agent + if agent_id is not None: + request.agent_id = agent_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_agent + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_agent( + self, + request: Optional[Union[agent_service.UpdateAgentRequest, dict]] = None, + *, + agent: Optional[gcc_agent.Agent] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_agent.Agent: + r"""Updates the specified agent. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_update_agent(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + agent = ces_v1beta.Agent() + agent.display_name = "display_name_value" + + request = ces_v1beta.UpdateAgentRequest( + agent=agent, + ) + + # Make the request + response = await client.update_agent(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.UpdateAgentRequest, dict]]): + The request object. Request message for + [AgentService.UpdateAgent][google.cloud.ces.v1beta.AgentService.UpdateAgent]. + agent (:class:`google.cloud.ces_v1beta.types.Agent`): + Required. The agent to update. + This corresponds to the ``agent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to + control which fields get updated. If the + mask is not present, all fields will be + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Agent: + An agent acts as the fundamental + building block that provides + instructions to the Large Language Model + (LLM) for executing specific tasks. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [agent, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.UpdateAgentRequest): + request = agent_service.UpdateAgentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if agent is not None: + request.agent = agent + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_agent + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("agent.name", request.agent.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_agent( + self, + request: Optional[Union[agent_service.DeleteAgentRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the specified agent. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_delete_agent(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteAgentRequest( + name="name_value", + ) + + # Make the request + await client.delete_agent(request=request) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.DeleteAgentRequest, dict]]): + The request object. Request message for + [AgentService.DeleteAgent][google.cloud.ces.v1beta.AgentService.DeleteAgent]. + name (:class:`str`): + Required. The resource name of the + agent to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.DeleteAgentRequest): + request = agent_service.DeleteAgentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_agent + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_examples( + self, + request: Optional[Union[agent_service.ListExamplesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListExamplesAsyncPager: + r"""Lists examples in the given app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_list_examples(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ListExamplesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_examples(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.ListExamplesRequest, dict]]): + The request object. Request message for + [AgentService.ListExamples][google.cloud.ces.v1beta.AgentService.ListExamples]. + parent (:class:`str`): + Required. The resource name of the + app to list examples from. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.services.agent_service.pagers.ListExamplesAsyncPager: + Response message for + [AgentService.ListExamples][google.cloud.ces.v1beta.AgentService.ListExamples]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.ListExamplesRequest): + request = agent_service.ListExamplesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_examples + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListExamplesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_example( + self, + request: Optional[Union[agent_service.GetExampleRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> example.Example: + r"""Gets details of the specified example. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_get_example(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.GetExampleRequest( + name="name_value", + ) + + # Make the request + response = await client.get_example(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.GetExampleRequest, dict]]): + The request object. Request message for + [AgentService.GetExample][google.cloud.ces.v1beta.AgentService.GetExample]. + name (:class:`str`): + Required. The resource name of the + example to retrieve. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Example: + An example represents a sample + conversation between the user and the + agent(s). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.GetExampleRequest): + request = agent_service.GetExampleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_example + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_example( + self, + request: Optional[Union[agent_service.CreateExampleRequest, dict]] = None, + *, + parent: Optional[str] = None, + example: Optional[gcc_example.Example] = None, + example_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_example.Example: + r"""Creates a new example in the given app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_create_example(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + example = ces_v1beta.Example() + example.display_name = "display_name_value" + + request = ces_v1beta.CreateExampleRequest( + parent="parent_value", + example=example, + ) + + # Make the request + response = await client.create_example(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.CreateExampleRequest, dict]]): + The request object. Request message for + [AgentService.CreateExample][google.cloud.ces.v1beta.AgentService.CreateExample]. + parent (:class:`str`): + Required. The resource name of the + app to create an example in. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + example (:class:`google.cloud.ces_v1beta.types.Example`): + Required. The example to create. + This corresponds to the ``example`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + example_id (:class:`str`): + Optional. The ID to use for the + example, which will become the final + component of the example's resource + name. If not provided, a unique ID will + be automatically assigned for the + example. + + This corresponds to the ``example_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Example: + An example represents a sample + conversation between the user and the + agent(s). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, example, example_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.CreateExampleRequest): + request = agent_service.CreateExampleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if example is not None: + request.example = example + if example_id is not None: + request.example_id = example_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_example + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_example( + self, + request: Optional[Union[agent_service.UpdateExampleRequest, dict]] = None, + *, + example: Optional[gcc_example.Example] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_example.Example: + r"""Updates the specified example. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_update_example(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + example = ces_v1beta.Example() + example.display_name = "display_name_value" + + request = ces_v1beta.UpdateExampleRequest( + example=example, + ) + + # Make the request + response = await client.update_example(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.UpdateExampleRequest, dict]]): + The request object. Request message for + [AgentService.UpdateExample][google.cloud.ces.v1beta.AgentService.UpdateExample]. + example (:class:`google.cloud.ces_v1beta.types.Example`): + Required. The example to update. + This corresponds to the ``example`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to + control which fields get updated. If the + mask is not present, all fields will be + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Example: + An example represents a sample + conversation between the user and the + agent(s). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [example, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.UpdateExampleRequest): + request = agent_service.UpdateExampleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if example is not None: + request.example = example + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_example + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("example.name", request.example.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_example( + self, + request: Optional[Union[agent_service.DeleteExampleRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the specified example. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_delete_example(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteExampleRequest( + name="name_value", + ) + + # Make the request + await client.delete_example(request=request) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.DeleteExampleRequest, dict]]): + The request object. Request message for + [AgentService.DeleteExample][google.cloud.ces.v1beta.AgentService.DeleteExample]. + name (:class:`str`): + Required. The resource name of the + example to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.DeleteExampleRequest): + request = agent_service.DeleteExampleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_example + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_tools( + self, + request: Optional[Union[agent_service.ListToolsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListToolsAsyncPager: + r"""Lists tools in the given app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_list_tools(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ListToolsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_tools(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.ListToolsRequest, dict]]): + The request object. Request message for + [AgentService.ListTools][google.cloud.ces.v1beta.AgentService.ListTools]. + parent (:class:`str`): + Required. The resource name of the + app to list tools from. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.services.agent_service.pagers.ListToolsAsyncPager: + Response message for + [AgentService.ListTools][google.cloud.ces.v1beta.AgentService.ListTools]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.ListToolsRequest): + request = agent_service.ListToolsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_tools + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListToolsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_tool( + self, + request: Optional[Union[agent_service.GetToolRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> tool.Tool: + r"""Gets details of the specified tool. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_get_tool(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.GetToolRequest( + name="name_value", + ) + + # Make the request + response = await client.get_tool(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.GetToolRequest, dict]]): + The request object. Request message for + [AgentService.GetTool][google.cloud.ces.v1beta.AgentService.GetTool]. + name (:class:`str`): + Required. The resource name of the + tool to retrieve. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Tool: + A tool represents an action that the + CES agent can take to achieve certain + goals. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.GetToolRequest): + request = agent_service.GetToolRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_tool] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_conversations( + self, + request: Optional[Union[agent_service.ListConversationsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListConversationsAsyncPager: + r"""Lists conversations in the given app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_list_conversations(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ListConversationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_conversations(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.ListConversationsRequest, dict]]): + The request object. Request message for + [AgentService.ListConversations][google.cloud.ces.v1beta.AgentService.ListConversations]. + parent (:class:`str`): + Required. The resource name of the + app to list conversations from. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.services.agent_service.pagers.ListConversationsAsyncPager: + Response message for + [AgentService.ListConversations][google.cloud.ces.v1beta.AgentService.ListConversations]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.ListConversationsRequest): + request = agent_service.ListConversationsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_conversations + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListConversationsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_conversation( + self, + request: Optional[Union[agent_service.GetConversationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> conversation.Conversation: + r"""Gets details of the specified conversation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_get_conversation(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.GetConversationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_conversation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.GetConversationRequest, dict]]): + The request object. Request message for + [AgentService.GetConversation][google.cloud.ces.v1beta.AgentService.GetConversation]. + name (:class:`str`): + Required. The resource name of the + conversation to retrieve. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Conversation: + A conversation represents an + interaction between an end user and the + CES app. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.GetConversationRequest): + request = agent_service.GetConversationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_conversation + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_conversation( + self, + request: Optional[Union[agent_service.DeleteConversationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the specified conversation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_delete_conversation(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteConversationRequest( + name="name_value", + ) + + # Make the request + await client.delete_conversation(request=request) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.DeleteConversationRequest, dict]]): + The request object. Request message for + [AgentService.DeleteConversation][google.cloud.ces.v1beta.AgentService.DeleteConversation]. + name (:class:`str`): + Required. The resource name of the + conversation to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.DeleteConversationRequest): + request = agent_service.DeleteConversationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_conversation + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def batch_delete_conversations( + self, + request: Optional[ + Union[agent_service.BatchDeleteConversationsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Batch deletes the specified conversations. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_batch_delete_conversations(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.BatchDeleteConversationsRequest( + parent="parent_value", + conversations=['conversations_value1', 'conversations_value2'], + ) + + # Make the request + operation = client.batch_delete_conversations(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.BatchDeleteConversationsRequest, dict]]): + The request object. Request message for + [AgentService.BatchDeleteConversations][google.cloud.ces.v1beta.AgentService.BatchDeleteConversations]. + parent (:class:`str`): + Required. The resource name of the app to delete + conversations from. Format: + ``projects/{project}/locations/{location}/apps/{app}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.ces_v1beta.types.BatchDeleteConversationsResponse` Response message for + [AgentService.BatchDeleteConversations][google.cloud.ces.v1beta.AgentService.BatchDeleteConversations]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.BatchDeleteConversationsRequest): + request = agent_service.BatchDeleteConversationsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.batch_delete_conversations + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + agent_service.BatchDeleteConversationsResponse, + metadata_type=agent_service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def create_tool( + self, + request: Optional[Union[agent_service.CreateToolRequest, dict]] = None, + *, + parent: Optional[str] = None, + tool: Optional[gcc_tool.Tool] = None, + tool_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_tool.Tool: + r"""Creates a new tool in the given app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_create_tool(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + tool = ces_v1beta.Tool() + tool.client_function.name = "name_value" + + request = ces_v1beta.CreateToolRequest( + parent="parent_value", + tool=tool, + ) + + # Make the request + response = await client.create_tool(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.CreateToolRequest, dict]]): + The request object. Request message for + [AgentService.CreateTool][google.cloud.ces.v1beta.AgentService.CreateTool]. + parent (:class:`str`): + Required. The resource name of the + app to create a tool in. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tool (:class:`google.cloud.ces_v1beta.types.Tool`): + Required. The tool to create. + This corresponds to the ``tool`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tool_id (:class:`str`): + Optional. The ID to use for the tool, + which will become the final component of + the tool's resource name. If not + provided, a unique ID will be + automatically assigned for the tool. + + This corresponds to the ``tool_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Tool: + A tool represents an action that the + CES agent can take to achieve certain + goals. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, tool, tool_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.CreateToolRequest): + request = agent_service.CreateToolRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if tool is not None: + request.tool = tool + if tool_id is not None: + request.tool_id = tool_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_tool + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_tool( + self, + request: Optional[Union[agent_service.UpdateToolRequest, dict]] = None, + *, + tool: Optional[gcc_tool.Tool] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_tool.Tool: + r"""Updates the specified tool. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_update_tool(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + tool = ces_v1beta.Tool() + tool.client_function.name = "name_value" + + request = ces_v1beta.UpdateToolRequest( + tool=tool, + ) + + # Make the request + response = await client.update_tool(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.UpdateToolRequest, dict]]): + The request object. Request message for + [AgentService.UpdateTool][google.cloud.ces.v1beta.AgentService.UpdateTool]. + tool (:class:`google.cloud.ces_v1beta.types.Tool`): + Required. The tool to update. + This corresponds to the ``tool`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to + control which fields get updated. If the + mask is not present, all fields will be + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Tool: + A tool represents an action that the + CES agent can take to achieve certain + goals. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [tool, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.UpdateToolRequest): + request = agent_service.UpdateToolRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if tool is not None: + request.tool = tool + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_tool + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("tool.name", request.tool.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_tool( + self, + request: Optional[Union[agent_service.DeleteToolRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the specified tool. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_delete_tool(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteToolRequest( + name="name_value", + ) + + # Make the request + await client.delete_tool(request=request) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.DeleteToolRequest, dict]]): + The request object. Request message for + [AgentService.DeleteTool][google.cloud.ces.v1beta.AgentService.DeleteTool]. + name (:class:`str`): + Required. The resource name of the + tool to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.DeleteToolRequest): + request = agent_service.DeleteToolRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_tool + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_guardrails( + self, + request: Optional[Union[agent_service.ListGuardrailsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListGuardrailsAsyncPager: + r"""Lists guardrails in the given app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_list_guardrails(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ListGuardrailsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_guardrails(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.ListGuardrailsRequest, dict]]): + The request object. Request message for + [AgentService.ListGuardrails][google.cloud.ces.v1beta.AgentService.ListGuardrails]. + parent (:class:`str`): + Required. The resource name of the + app to list guardrails from. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.services.agent_service.pagers.ListGuardrailsAsyncPager: + Response message for + [AgentService.ListGuardrails][google.cloud.ces.v1beta.AgentService.ListGuardrails]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.ListGuardrailsRequest): + request = agent_service.ListGuardrailsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_guardrails + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListGuardrailsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_guardrail( + self, + request: Optional[Union[agent_service.GetGuardrailRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> guardrail.Guardrail: + r"""Gets details of the specified guardrail. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_get_guardrail(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.GetGuardrailRequest( + name="name_value", + ) + + # Make the request + response = await client.get_guardrail(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.GetGuardrailRequest, dict]]): + The request object. Request message for + [AgentService.GetGuardrail][google.cloud.ces.v1beta.AgentService.GetGuardrail]. + name (:class:`str`): + Required. The resource name of the + guardrail to retrieve. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Guardrail: + Guardrail contains a list of checks + and balances to keep the agents safe and + secure. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.GetGuardrailRequest): + request = agent_service.GetGuardrailRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_guardrail + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_guardrail( + self, + request: Optional[Union[agent_service.CreateGuardrailRequest, dict]] = None, + *, + parent: Optional[str] = None, + guardrail: Optional[gcc_guardrail.Guardrail] = None, + guardrail_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_guardrail.Guardrail: + r"""Creates a new guardrail in the given app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_create_guardrail(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + guardrail = ces_v1beta.Guardrail() + guardrail.content_filter.match_type = "REGEXP_MATCH" + guardrail.display_name = "display_name_value" + + request = ces_v1beta.CreateGuardrailRequest( + parent="parent_value", + guardrail=guardrail, + ) + + # Make the request + response = await client.create_guardrail(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.CreateGuardrailRequest, dict]]): + The request object. Request message for + [AgentService.CreateGuardrail][google.cloud.ces.v1beta.AgentService.CreateGuardrail]. + parent (:class:`str`): + Required. The resource name of the + app to create a guardrail in. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + guardrail (:class:`google.cloud.ces_v1beta.types.Guardrail`): + Required. The guardrail to create. + This corresponds to the ``guardrail`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + guardrail_id (:class:`str`): + Optional. The ID to use for the + guardrail, which will become the final + component of the guardrail's resource + name. If not provided, a unique ID will + be automatically assigned for the + guardrail. + + This corresponds to the ``guardrail_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Guardrail: + Guardrail contains a list of checks + and balances to keep the agents safe and + secure. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, guardrail, guardrail_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.CreateGuardrailRequest): + request = agent_service.CreateGuardrailRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if guardrail is not None: + request.guardrail = guardrail + if guardrail_id is not None: + request.guardrail_id = guardrail_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_guardrail + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_guardrail( + self, + request: Optional[Union[agent_service.UpdateGuardrailRequest, dict]] = None, + *, + guardrail: Optional[gcc_guardrail.Guardrail] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_guardrail.Guardrail: + r"""Updates the specified guardrail. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_update_guardrail(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + guardrail = ces_v1beta.Guardrail() + guardrail.content_filter.match_type = "REGEXP_MATCH" + guardrail.display_name = "display_name_value" + + request = ces_v1beta.UpdateGuardrailRequest( + guardrail=guardrail, + ) + + # Make the request + response = await client.update_guardrail(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.UpdateGuardrailRequest, dict]]): + The request object. Request message for + [AgentService.UpdateGuardrail][google.cloud.ces.v1beta.AgentService.UpdateGuardrail]. + guardrail (:class:`google.cloud.ces_v1beta.types.Guardrail`): + Required. The guardrail to update. + This corresponds to the ``guardrail`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to + control which fields get updated. If the + mask is not present, all fields will be + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Guardrail: + Guardrail contains a list of checks + and balances to keep the agents safe and + secure. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [guardrail, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.UpdateGuardrailRequest): + request = agent_service.UpdateGuardrailRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if guardrail is not None: + request.guardrail = guardrail + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_guardrail + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("guardrail.name", request.guardrail.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_guardrail( + self, + request: Optional[Union[agent_service.DeleteGuardrailRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the specified guardrail. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_delete_guardrail(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteGuardrailRequest( + name="name_value", + ) + + # Make the request + await client.delete_guardrail(request=request) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.DeleteGuardrailRequest, dict]]): + The request object. Request message for + [AgentService.DeleteGuardrail][google.cloud.ces.v1beta.AgentService.DeleteGuardrail]. + name (:class:`str`): + Required. The resource name of the + guardrail to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.DeleteGuardrailRequest): + request = agent_service.DeleteGuardrailRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_guardrail + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_deployments( + self, + request: Optional[Union[agent_service.ListDeploymentsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListDeploymentsAsyncPager: + r"""Lists deployments in the given app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_list_deployments(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ListDeploymentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_deployments(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.ListDeploymentsRequest, dict]]): + The request object. Request message for + [AgentService.ListDeployments][google.cloud.ces.v1beta.AgentService.ListDeployments]. + parent (:class:`str`): + Required. The parent app. Format: + ``projects/{project}/locations/{location}/apps/{app}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.services.agent_service.pagers.ListDeploymentsAsyncPager: + Response message for + [AgentService.ListDeployments][google.cloud.ces.v1beta.AgentService.ListDeployments]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.ListDeploymentsRequest): + request = agent_service.ListDeploymentsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_deployments + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListDeploymentsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_deployment( + self, + request: Optional[Union[agent_service.GetDeploymentRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> deployment.Deployment: + r"""Gets details of the specified deployment. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_get_deployment(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.GetDeploymentRequest( + name="name_value", + ) + + # Make the request + response = await client.get_deployment(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.GetDeploymentRequest, dict]]): + The request object. Request message for + [AgentService.GetDeployment][google.cloud.ces.v1beta.AgentService.GetDeployment]. + name (:class:`str`): + Required. The name of the deployment. Format: + ``projects/{project}/locations/{location}/apps/{app}/deployments/{deployment}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Deployment: + A deployment represents an immutable, + queryable version of the app. It is used + to deploy an app version with a specific + channel profile. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.GetDeploymentRequest): + request = agent_service.GetDeploymentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_deployment + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_deployment( + self, + request: Optional[Union[agent_service.CreateDeploymentRequest, dict]] = None, + *, + parent: Optional[str] = None, + deployment: Optional[gcc_deployment.Deployment] = None, + deployment_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_deployment.Deployment: + r"""Creates a new deployment in the given app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_create_deployment(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + deployment = ces_v1beta.Deployment() + deployment.display_name = "display_name_value" + + request = ces_v1beta.CreateDeploymentRequest( + parent="parent_value", + deployment=deployment, + ) + + # Make the request + response = await client.create_deployment(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.CreateDeploymentRequest, dict]]): + The request object. Request message for + [AgentService.CreateDeployment][google.cloud.ces.v1beta.AgentService.CreateDeployment]. + parent (:class:`str`): + Required. The parent app. Format: + ``projects/{project}/locations/{location}/apps/{app}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + deployment (:class:`google.cloud.ces_v1beta.types.Deployment`): + Required. The deployment to create. + This corresponds to the ``deployment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + deployment_id (:class:`str`): + Optional. The ID to use for the + deployment, which will become the final + component of the deployment's resource + name. If not provided, a unique ID will + be automatically assigned for the + deployment. + + This corresponds to the ``deployment_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Deployment: + A deployment represents an immutable, + queryable version of the app. It is used + to deploy an app version with a specific + channel profile. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, deployment, deployment_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.CreateDeploymentRequest): + request = agent_service.CreateDeploymentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if deployment is not None: + request.deployment = deployment + if deployment_id is not None: + request.deployment_id = deployment_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_deployment + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_deployment( + self, + request: Optional[Union[agent_service.UpdateDeploymentRequest, dict]] = None, + *, + deployment: Optional[gcc_deployment.Deployment] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_deployment.Deployment: + r"""Updates the specified deployment. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_update_deployment(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + deployment = ces_v1beta.Deployment() + deployment.display_name = "display_name_value" + + request = ces_v1beta.UpdateDeploymentRequest( + deployment=deployment, + ) + + # Make the request + response = await client.update_deployment(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.UpdateDeploymentRequest, dict]]): + The request object. Request message for + [AgentService.UpdateDeployment][google.cloud.ces.v1beta.AgentService.UpdateDeployment]. + deployment (:class:`google.cloud.ces_v1beta.types.Deployment`): + Required. The deployment to update. + This corresponds to the ``deployment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. The list of fields to + update. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Deployment: + A deployment represents an immutable, + queryable version of the app. It is used + to deploy an app version with a specific + channel profile. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [deployment, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.UpdateDeploymentRequest): + request = agent_service.UpdateDeploymentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if deployment is not None: + request.deployment = deployment + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_deployment + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("deployment.name", request.deployment.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_deployment( + self, + request: Optional[Union[agent_service.DeleteDeploymentRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the specified deployment. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_delete_deployment(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteDeploymentRequest( + name="name_value", + ) + + # Make the request + await client.delete_deployment(request=request) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.DeleteDeploymentRequest, dict]]): + The request object. Request message for + [AgentService.DeleteDeployment][google.cloud.ces.v1beta.AgentService.DeleteDeployment]. + name (:class:`str`): + Required. The name of the deployment to delete. Format: + ``projects/{project}/locations/{location}/apps/{app}/deployments/{deployment}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.DeleteDeploymentRequest): + request = agent_service.DeleteDeploymentRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_deployment + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_toolsets( + self, + request: Optional[Union[agent_service.ListToolsetsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListToolsetsAsyncPager: + r"""Lists toolsets in the given app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_list_toolsets(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ListToolsetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_toolsets(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.ListToolsetsRequest, dict]]): + The request object. Request message for + [AgentService.ListToolsets][google.cloud.ces.v1beta.AgentService.ListToolsets]. + parent (:class:`str`): + Required. The resource name of the + app to list toolsets from. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.services.agent_service.pagers.ListToolsetsAsyncPager: + Response message for + [AgentService.ListToolsets][google.cloud.ces.v1beta.AgentService.ListToolsets]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.ListToolsetsRequest): + request = agent_service.ListToolsetsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_toolsets + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListToolsetsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_toolset( + self, + request: Optional[Union[agent_service.GetToolsetRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> toolset.Toolset: + r"""Gets details of the specified toolset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_get_toolset(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.GetToolsetRequest( + name="name_value", + ) + + # Make the request + response = await client.get_toolset(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.GetToolsetRequest, dict]]): + The request object. Request message for + [AgentService.GetToolset][google.cloud.ces.v1beta.AgentService.GetToolset]. + name (:class:`str`): + Required. The resource name of the + toolset to retrieve. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Toolset: + A toolset represents a group of + dynamically managed tools that can be + used by the agent. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.GetToolsetRequest): + request = agent_service.GetToolsetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_toolset + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_toolset( + self, + request: Optional[Union[agent_service.CreateToolsetRequest, dict]] = None, + *, + parent: Optional[str] = None, + toolset: Optional[gcc_toolset.Toolset] = None, + toolset_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_toolset.Toolset: + r"""Creates a new toolset in the given app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_create_toolset(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + toolset = ces_v1beta.Toolset() + toolset.mcp_toolset.server_address = "server_address_value" + + request = ces_v1beta.CreateToolsetRequest( + parent="parent_value", + toolset=toolset, + ) + + # Make the request + response = await client.create_toolset(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.CreateToolsetRequest, dict]]): + The request object. Request message for + [AgentService.CreateToolset][google.cloud.ces.v1beta.AgentService.CreateToolset]. + parent (:class:`str`): + Required. The resource name of the + app to create a toolset in. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + toolset (:class:`google.cloud.ces_v1beta.types.Toolset`): + Required. The toolset to create. + This corresponds to the ``toolset`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + toolset_id (:class:`str`): + Optional. The ID to use for the + toolset, which will become the final + component of the toolset's resource + name. If not provided, a unique ID will + be automatically assigned for the + toolset. + + This corresponds to the ``toolset_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Toolset: + A toolset represents a group of + dynamically managed tools that can be + used by the agent. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, toolset, toolset_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.CreateToolsetRequest): + request = agent_service.CreateToolsetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if toolset is not None: + request.toolset = toolset + if toolset_id is not None: + request.toolset_id = toolset_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_toolset + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_toolset( + self, + request: Optional[Union[agent_service.UpdateToolsetRequest, dict]] = None, + *, + toolset: Optional[gcc_toolset.Toolset] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_toolset.Toolset: + r"""Updates the specified toolset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_update_toolset(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + toolset = ces_v1beta.Toolset() + toolset.mcp_toolset.server_address = "server_address_value" + + request = ces_v1beta.UpdateToolsetRequest( + toolset=toolset, + ) + + # Make the request + response = await client.update_toolset(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.UpdateToolsetRequest, dict]]): + The request object. Request message for + [AgentService.UpdateToolset][google.cloud.ces.v1beta.AgentService.UpdateToolset]. + toolset (:class:`google.cloud.ces_v1beta.types.Toolset`): + Required. The toolset to update. + This corresponds to the ``toolset`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to + control which fields get updated. If the + mask is not present, all fields will be + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Toolset: + A toolset represents a group of + dynamically managed tools that can be + used by the agent. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [toolset, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.UpdateToolsetRequest): + request = agent_service.UpdateToolsetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if toolset is not None: + request.toolset = toolset + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_toolset + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("toolset.name", request.toolset.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_toolset( + self, + request: Optional[Union[agent_service.DeleteToolsetRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the specified toolset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_delete_toolset(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteToolsetRequest( + name="name_value", + ) + + # Make the request + await client.delete_toolset(request=request) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.DeleteToolsetRequest, dict]]): + The request object. Request message for + [AgentService.DeleteToolset][google.cloud.ces.v1beta.AgentService.DeleteToolset]. + name (:class:`str`): + Required. The resource name of the + toolset to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.DeleteToolsetRequest): + request = agent_service.DeleteToolsetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_toolset + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def list_app_versions( + self, + request: Optional[Union[agent_service.ListAppVersionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAppVersionsAsyncPager: + r"""Lists all app versions in the given app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_list_app_versions(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ListAppVersionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_app_versions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.ListAppVersionsRequest, dict]]): + The request object. Request message for + [AgentService.ListAppVersions][google.cloud.ces.v1beta.AgentService.ListAppVersions]. + parent (:class:`str`): + Required. The resource name of the + app to list app versions from. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.services.agent_service.pagers.ListAppVersionsAsyncPager: + Response message for + [AgentService.ListAppVersions][google.cloud.ces.v1beta.AgentService.ListAppVersions]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.ListAppVersionsRequest): + request = agent_service.ListAppVersionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_app_versions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListAppVersionsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_app_version( + self, + request: Optional[Union[agent_service.GetAppVersionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> app_version.AppVersion: + r"""Gets details of the specified app version. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_get_app_version(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.GetAppVersionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_app_version(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.GetAppVersionRequest, dict]]): + The request object. Request message for + [AgentService.GetAppVersion][google.cloud.ces.v1beta.AgentService.GetAppVersion]. + name (:class:`str`): + Required. The resource name of the + app version to retrieve. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.AppVersion: + In Customer Engagement Suite (CES), + an app version is a snapshot of the app + at a specific point in time. It is + immutable and cannot be modified once + created. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.GetAppVersionRequest): + request = agent_service.GetAppVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_app_version + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_app_version( + self, + request: Optional[Union[agent_service.CreateAppVersionRequest, dict]] = None, + *, + parent: Optional[str] = None, + app_version: Optional[gcc_app_version.AppVersion] = None, + app_version_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_app_version.AppVersion: + r"""Creates a new app version in the given app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_create_app_version(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.CreateAppVersionRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_app_version(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.CreateAppVersionRequest, dict]]): + The request object. Request message for + [AgentService.CreateAppVersion][google.cloud.ces.v1beta.AgentService.CreateAppVersion] + parent (:class:`str`): + Required. The resource name of the + app to create an app version in. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + app_version (:class:`google.cloud.ces_v1beta.types.AppVersion`): + Required. The app version to create. + This corresponds to the ``app_version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + app_version_id (:class:`str`): + Optional. The ID to use for the app + version, which will become the final + component of the app version's resource + name. If not provided, a unique ID will + be automatically assigned for the app + version. + + This corresponds to the ``app_version_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.AppVersion: + In Customer Engagement Suite (CES), + an app version is a snapshot of the app + at a specific point in time. It is + immutable and cannot be modified once + created. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, app_version, app_version_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.CreateAppVersionRequest): + request = agent_service.CreateAppVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if app_version is not None: + request.app_version = app_version + if app_version_id is not None: + request.app_version_id = app_version_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_app_version + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_app_version( + self, + request: Optional[Union[agent_service.DeleteAppVersionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the specified app version. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_delete_app_version(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteAppVersionRequest( + name="name_value", + ) + + # Make the request + await client.delete_app_version(request=request) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.DeleteAppVersionRequest, dict]]): + The request object. Request message for + [AgentService.DeleteAppVersion][google.cloud.ces.v1beta.AgentService.DeleteAppVersion]. + name (:class:`str`): + Required. The resource name of the + app version to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.DeleteAppVersionRequest): + request = agent_service.DeleteAppVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_app_version + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def restore_app_version( + self, + request: Optional[Union[agent_service.RestoreAppVersionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Restores the specified app version. + This will create a new app version from the current + draft app and overwrite the current draft with the + specified app version. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_restore_app_version(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.RestoreAppVersionRequest( + name="name_value", + ) + + # Make the request + operation = client.restore_app_version(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.RestoreAppVersionRequest, dict]]): + The request object. Request message for + [AgentService.RestoreAppVersion][google.cloud.ces.v1beta.AgentService.RestoreAppVersion] + name (:class:`str`): + Required. The resource name of the + app version to restore. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.ces_v1beta.types.RestoreAppVersionResponse` Response message for + [AgentService.RestoreAppVersion][google.cloud.ces.v1beta.AgentService.RestoreAppVersion] + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.RestoreAppVersionRequest): + request = agent_service.RestoreAppVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.restore_app_version + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + agent_service.RestoreAppVersionResponse, + metadata_type=agent_service.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_changelogs( + self, + request: Optional[Union[agent_service.ListChangelogsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListChangelogsAsyncPager: + r"""Lists the changelogs of the specified app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_list_changelogs(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ListChangelogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_changelogs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.ListChangelogsRequest, dict]]): + The request object. Request message for + [AgentService.ListChangelogs][google.cloud.ces.v1beta.AgentService.ListChangelogs]. + parent (:class:`str`): + Required. The resource name of the + app to list changelogs from. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.services.agent_service.pagers.ListChangelogsAsyncPager: + Response message for + [AgentService.ListChangelogs][google.cloud.ces.v1beta.AgentService.ListChangelogs]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.ListChangelogsRequest): + request = agent_service.ListChangelogsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_changelogs + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListChangelogsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_changelog( + self, + request: Optional[Union[agent_service.GetChangelogRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> changelog.Changelog: + r"""Gets the specified changelog. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_get_changelog(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.GetChangelogRequest( + name="name_value", + ) + + # Make the request + response = await client.get_changelog(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.GetChangelogRequest, dict]]): + The request object. Request message for + [AgentService.GetChangelog][google.cloud.ces.v1beta.AgentService.GetChangelog]. + name (:class:`str`): + Required. The resource name of the + changelog to retrieve. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Changelog: + Changelogs represent a change made to + the app or to an resource within the + app. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.GetChangelogRequest): + request = agent_service.GetChangelogRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_changelog + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.delete_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "AgentServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("AgentServiceAsyncClient",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/client.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/client.py new file mode 100644 index 000000000000..12db6430b255 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/client.py @@ -0,0 +1,7216 @@ +# -*- coding: utf-8 -*- +# 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. +# +import json +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.ces_v1beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.struct_pb2 as struct_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.ces_v1beta.services.agent_service import pagers +from google.cloud.ces_v1beta.types import ( + agent, + agent_service, + agent_transfers, + app, + app_version, + changelog, + client_function, + common, + connector_tool, + connector_toolset, + conversation, + data_store_tool, + deployment, + example, + fakes, + file_search_tool, + google_search_tool, + guardrail, + mcp_tool, + mcp_toolset, + open_api_tool, + open_api_toolset, + python_function, + system_tool, + tool, + toolset, + widget_tool, +) +from google.cloud.ces_v1beta.types import agent as gcc_agent +from google.cloud.ces_v1beta.types import app as gcc_app +from google.cloud.ces_v1beta.types import app_version as gcc_app_version +from google.cloud.ces_v1beta.types import deployment as gcc_deployment +from google.cloud.ces_v1beta.types import example as gcc_example +from google.cloud.ces_v1beta.types import guardrail as gcc_guardrail +from google.cloud.ces_v1beta.types import tool as gcc_tool +from google.cloud.ces_v1beta.types import toolset as gcc_toolset + +from .transports.base import DEFAULT_CLIENT_INFO, AgentServiceTransport +from .transports.grpc import AgentServiceGrpcTransport +from .transports.grpc_asyncio import AgentServiceGrpcAsyncIOTransport +from .transports.rest import AgentServiceRestTransport + + +class AgentServiceClientMeta(type): + """Metaclass for the AgentService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[AgentServiceTransport]] + _transport_registry["grpc"] = AgentServiceGrpcTransport + _transport_registry["grpc_asyncio"] = AgentServiceGrpcAsyncIOTransport + _transport_registry["rest"] = AgentServiceRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[AgentServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class AgentServiceClient(metaclass=AgentServiceClientMeta): + """The service that manages agent-related resources in Gemini + Enterprise for Customer Engagement (CES). + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "ces.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "ces.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + AgentServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + AgentServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> AgentServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AgentServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def agent_path( + project: str, + location: str, + app: str, + agent: str, + ) -> str: + """Returns a fully-qualified agent string.""" + return ( + "projects/{project}/locations/{location}/apps/{app}/agents/{agent}".format( + project=project, + location=location, + app=app, + agent=agent, + ) + ) + + @staticmethod + def parse_agent_path(path: str) -> Dict[str, str]: + """Parses a agent path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/apps/(?P.+?)/agents/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def app_path( + project: str, + location: str, + app: str, + ) -> str: + """Returns a fully-qualified app string.""" + return "projects/{project}/locations/{location}/apps/{app}".format( + project=project, + location=location, + app=app, + ) + + @staticmethod + def parse_app_path(path: str) -> Dict[str, str]: + """Parses a app path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/apps/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def app_version_path( + project: str, + location: str, + app: str, + version: str, + ) -> str: + """Returns a fully-qualified app_version string.""" + return "projects/{project}/locations/{location}/apps/{app}/versions/{version}".format( + project=project, + location=location, + app=app, + version=version, + ) + + @staticmethod + def parse_app_version_path(path: str) -> Dict[str, str]: + """Parses a app_version path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/apps/(?P.+?)/versions/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def changelog_path( + project: str, + location: str, + app: str, + changelog: str, + ) -> str: + """Returns a fully-qualified changelog string.""" + return "projects/{project}/locations/{location}/apps/{app}/changelogs/{changelog}".format( + project=project, + location=location, + app=app, + changelog=changelog, + ) + + @staticmethod + def parse_changelog_path(path: str) -> Dict[str, str]: + """Parses a changelog path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/apps/(?P.+?)/changelogs/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def conversation_path( + project: str, + location: str, + app: str, + conversation: str, + ) -> str: + """Returns a fully-qualified conversation string.""" + return "projects/{project}/locations/{location}/apps/{app}/conversations/{conversation}".format( + project=project, + location=location, + app=app, + conversation=conversation, + ) + + @staticmethod + def parse_conversation_path(path: str) -> Dict[str, str]: + """Parses a conversation path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/apps/(?P.+?)/conversations/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def deidentify_template_path( + organization: str, + location: str, + deidentify_template: str, + ) -> str: + """Returns a fully-qualified deidentify_template string.""" + return "organizations/{organization}/locations/{location}/deidentifyTemplates/{deidentify_template}".format( + organization=organization, + location=location, + deidentify_template=deidentify_template, + ) + + @staticmethod + def parse_deidentify_template_path(path: str) -> Dict[str, str]: + """Parses a deidentify_template path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/locations/(?P.+?)/deidentifyTemplates/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def deployment_path( + project: str, + location: str, + app: str, + deployment: str, + ) -> str: + """Returns a fully-qualified deployment string.""" + return "projects/{project}/locations/{location}/apps/{app}/deployments/{deployment}".format( + project=project, + location=location, + app=app, + deployment=deployment, + ) + + @staticmethod + def parse_deployment_path(path: str) -> Dict[str, str]: + """Parses a deployment path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/apps/(?P.+?)/deployments/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def dialogflow_agent_path( + project: str, + location: str, + agent: str, + ) -> str: + """Returns a fully-qualified dialogflow_agent string.""" + return "projects/{project}/locations/{location}/agents/{agent}".format( + project=project, + location=location, + agent=agent, + ) + + @staticmethod + def parse_dialogflow_agent_path(path: str) -> Dict[str, str]: + """Parses a dialogflow_agent path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/agents/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def engine_path( + project: str, + location: str, + collection: str, + engine: str, + ) -> str: + """Returns a fully-qualified engine string.""" + return "projects/{project}/locations/{location}/collections/{collection}/engines/{engine}".format( + project=project, + location=location, + collection=collection, + engine=engine, + ) + + @staticmethod + def parse_engine_path(path: str) -> Dict[str, str]: + """Parses a engine path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/collections/(?P.+?)/engines/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def example_path( + project: str, + location: str, + app: str, + example: str, + ) -> str: + """Returns a fully-qualified example string.""" + return "projects/{project}/locations/{location}/apps/{app}/examples/{example}".format( + project=project, + location=location, + app=app, + example=example, + ) + + @staticmethod + def parse_example_path(path: str) -> Dict[str, str]: + """Parses a example path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/apps/(?P.+?)/examples/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def guardrail_path( + project: str, + location: str, + app: str, + guardrail: str, + ) -> str: + """Returns a fully-qualified guardrail string.""" + return "projects/{project}/locations/{location}/apps/{app}/guardrails/{guardrail}".format( + project=project, + location=location, + app=app, + guardrail=guardrail, + ) + + @staticmethod + def parse_guardrail_path(path: str) -> Dict[str, str]: + """Parses a guardrail path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/apps/(?P.+?)/guardrails/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def inspect_template_path( + organization: str, + location: str, + inspect_template: str, + ) -> str: + """Returns a fully-qualified inspect_template string.""" + return "organizations/{organization}/locations/{location}/inspectTemplates/{inspect_template}".format( + organization=organization, + location=location, + inspect_template=inspect_template, + ) + + @staticmethod + def parse_inspect_template_path(path: str) -> Dict[str, str]: + """Parses a inspect_template path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/locations/(?P.+?)/inspectTemplates/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def secret_version_path( + project: str, + secret: str, + secret_version: str, + ) -> str: + """Returns a fully-qualified secret_version string.""" + return "projects/{project}/secrets/{secret}/versions/{secret_version}".format( + project=project, + secret=secret, + secret_version=secret_version, + ) + + @staticmethod + def parse_secret_version_path(path: str) -> Dict[str, str]: + """Parses a secret_version path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/secrets/(?P.+?)/versions/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def service_path( + project: str, + location: str, + namespace: str, + service: str, + ) -> str: + """Returns a fully-qualified service string.""" + return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format( + project=project, + location=location, + namespace=namespace, + service=service, + ) + + @staticmethod + def parse_service_path(path: str) -> Dict[str, str]: + """Parses a service path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)/services/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def tool_path( + project: str, + location: str, + app: str, + tool: str, + ) -> str: + """Returns a fully-qualified tool string.""" + return "projects/{project}/locations/{location}/apps/{app}/tools/{tool}".format( + project=project, + location=location, + app=app, + tool=tool, + ) + + @staticmethod + def parse_tool_path(path: str) -> Dict[str, str]: + """Parses a tool path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/apps/(?P.+?)/tools/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def toolset_path( + project: str, + location: str, + app: str, + toolset: str, + ) -> str: + """Returns a fully-qualified toolset string.""" + return "projects/{project}/locations/{location}/apps/{app}/toolsets/{toolset}".format( + project=project, + location=location, + app=app, + toolset=toolset, + ) + + @staticmethod + def parse_toolset_path(path: str) -> Dict[str, str]: + """Parses a toolset path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/apps/(?P.+?)/toolsets/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = AgentServiceClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = AgentServiceClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = AgentServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = AgentServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = AgentServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = AgentServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, AgentServiceTransport, Callable[..., AgentServiceTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the agent service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,AgentServiceTransport,Callable[..., AgentServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the AgentServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + AgentServiceClient._read_environment_variables() + ) + self._client_cert_source = AgentServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = AgentServiceClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, AgentServiceTransport) + if transport_provided: + # transport is a AgentServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(AgentServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = self._api_endpoint or AgentServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[AgentServiceTransport], Callable[..., AgentServiceTransport] + ] = ( + AgentServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., AgentServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.ces_v1beta.AgentServiceClient`.", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.cloud.ces.v1beta.AgentService", + "credentialsType": None, + }, + ) + + def list_apps( + self, + request: Optional[Union[agent_service.ListAppsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAppsPager: + r"""Lists apps in the given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_list_apps(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ListAppsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_apps(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.ListAppsRequest, dict]): + The request object. Request message for + [AgentService.ListApps][google.cloud.ces.v1beta.AgentService.ListApps]. + parent (str): + Required. The resource name of the + location to list apps from. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.services.agent_service.pagers.ListAppsPager: + Response message for + [AgentService.ListApps][google.cloud.ces.v1beta.AgentService.ListApps]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.ListAppsRequest): + request = agent_service.ListAppsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_apps] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListAppsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_app( + self, + request: Optional[Union[agent_service.GetAppRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> app.App: + r"""Gets details of the specified app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_get_app(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.GetAppRequest( + name="name_value", + ) + + # Make the request + response = client.get_app(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.GetAppRequest, dict]): + The request object. Request message for + [AgentService.GetApp][google.cloud.ces.v1beta.AgentService.GetApp]. + name (str): + Required. The resource name of the + app to retrieve. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.App: + An app serves as a top-level + container for a group of agents, + including the root agent and its + sub-agents, along with their associated + configurations. These agents work + together to achieve specific goals + within the app's context. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.GetAppRequest): + request = agent_service.GetAppRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_app] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_app( + self, + request: Optional[Union[agent_service.CreateAppRequest, dict]] = None, + *, + parent: Optional[str] = None, + app: Optional[gcc_app.App] = None, + app_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a new app in the given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_create_app(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + app = ces_v1beta.App() + app.display_name = "display_name_value" + + request = ces_v1beta.CreateAppRequest( + parent="parent_value", + app=app, + ) + + # Make the request + operation = client.create_app(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.CreateAppRequest, dict]): + The request object. Request message for + [AgentService.CreateApp][google.cloud.ces.v1beta.AgentService.CreateApp]. + parent (str): + Required. The resource name of the + location to create an app in. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + app (google.cloud.ces_v1beta.types.App): + Required. The app to create. + This corresponds to the ``app`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + app_id (str): + Optional. The ID to use for the app, + which will become the final component of + the app's resource name. If not + provided, a unique ID will be + automatically assigned for the app. + + This corresponds to the ``app_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.ces_v1beta.types.App` An app serves as a top-level container for a group of agents, including the + root agent and its sub-agents, along with their + associated configurations. These agents work together + to achieve specific goals within the app's context. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, app, app_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.CreateAppRequest): + request = agent_service.CreateAppRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if app is not None: + request.app = app + if app_id is not None: + request.app_id = app_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_app] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gcc_app.App, + metadata_type=agent_service.OperationMetadata, + ) + + # Done; return the response. + return response + + def update_app( + self, + request: Optional[Union[agent_service.UpdateAppRequest, dict]] = None, + *, + app: Optional[gcc_app.App] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_app.App: + r"""Updates the specified app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_update_app(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + app = ces_v1beta.App() + app.display_name = "display_name_value" + + request = ces_v1beta.UpdateAppRequest( + app=app, + ) + + # Make the request + response = client.update_app(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.UpdateAppRequest, dict]): + The request object. Request message for + [AgentService.UpdateApp][google.cloud.ces.v1beta.AgentService.UpdateApp]. + app (google.cloud.ces_v1beta.types.App): + Required. The app to update. + This corresponds to the ``app`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to + control which fields get updated. If the + mask is not present, all fields will be + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.App: + An app serves as a top-level + container for a group of agents, + including the root agent and its + sub-agents, along with their associated + configurations. These agents work + together to achieve specific goals + within the app's context. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [app, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.UpdateAppRequest): + request = agent_service.UpdateAppRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if app is not None: + request.app = app + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_app] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("app.name", request.app.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_app( + self, + request: Optional[Union[agent_service.DeleteAppRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes the specified app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_delete_app(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteAppRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_app(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.DeleteAppRequest, dict]): + The request object. Request message for + [AgentService.DeleteApp][google.cloud.ces.v1beta.AgentService.DeleteApp]. + name (str): + Required. The resource name of the + app to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.DeleteAppRequest): + request = agent_service.DeleteAppRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_app] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=agent_service.OperationMetadata, + ) + + # Done; return the response. + return response + + def export_app( + self, + request: Optional[Union[agent_service.ExportAppRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Exports the specified app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_export_app(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ExportAppRequest( + name="name_value", + export_format="YAML", + ) + + # Make the request + operation = client.export_app(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.ExportAppRequest, dict]): + The request object. Request message for + [AgentService.ExportApp][google.cloud.ces.v1beta.AgentService.ExportApp]. + name (str): + Required. The resource name of the + app to export. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.ces_v1beta.types.ExportAppResponse` Response message for + [AgentService.ExportApp][google.cloud.ces.v1beta.AgentService.ExportApp]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.ExportAppRequest): + request = agent_service.ExportAppRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.export_app] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + agent_service.ExportAppResponse, + metadata_type=agent_service.OperationMetadata, + ) + + # Done; return the response. + return response + + def import_app( + self, + request: Optional[Union[agent_service.ImportAppRequest, dict]] = None, + *, + parent: Optional[str] = None, + display_name: Optional[str] = None, + app_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Imports the specified app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_import_app(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ImportAppRequest( + gcs_uri="gcs_uri_value", + parent="parent_value", + ) + + # Make the request + operation = client.import_app(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.ImportAppRequest, dict]): + The request object. Request message for + [AgentService.ImportApp][google.cloud.ces.v1beta.AgentService.ImportApp]. + parent (str): + Required. The parent resource name + with the location of the app to import. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + display_name (str): + Optional. The display name of the app to import. + + - If the app is created on import, and the display name + is specified, the imported app will use this display + name. If a conflict is detected with an existing app, + a timestamp will be appended to the display name to + make it unique. + - If the app is a reimport, this field should not be + set. Providing a display name during reimport will + result in an INVALID_ARGUMENT error. + + This corresponds to the ``display_name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + app_id (str): + Optional. The ID to use for the imported app. + + - If not specified, a unique ID will be automatically + assigned for the app. + - Otherwise, the imported app will use this ID as the + final component of its resource name. If an app with + the same ID already exists at the specified location + in the project, the content of the existing app will + be replaced. + + This corresponds to the ``app_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.ces_v1beta.types.ImportAppResponse` Response message for + [AgentService.ImportApp][google.cloud.ces.v1beta.AgentService.ImportApp]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, display_name, app_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.ImportAppRequest): + request = agent_service.ImportAppRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if display_name is not None: + request.display_name = display_name + if app_id is not None: + request.app_id = app_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_app] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + agent_service.ImportAppResponse, + metadata_type=agent_service.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_agents( + self, + request: Optional[Union[agent_service.ListAgentsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAgentsPager: + r"""Lists agents in the given app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_list_agents(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ListAgentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_agents(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.ListAgentsRequest, dict]): + The request object. Request message for + [AgentService.ListAgents][google.cloud.ces.v1beta.AgentService.ListAgents]. + parent (str): + Required. The resource name of the + app to list agents from. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.services.agent_service.pagers.ListAgentsPager: + Response message for + [AgentService.ListAgents][google.cloud.ces.v1beta.AgentService.ListAgents]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.ListAgentsRequest): + request = agent_service.ListAgentsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_agents] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListAgentsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_agent( + self, + request: Optional[Union[agent_service.GetAgentRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> agent.Agent: + r"""Gets details of the specified agent. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_get_agent(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.GetAgentRequest( + name="name_value", + ) + + # Make the request + response = client.get_agent(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.GetAgentRequest, dict]): + The request object. Request message for + [AgentService.GetAgent][google.cloud.ces.v1beta.AgentService.GetAgent]. + name (str): + Required. The resource name of the + agent to retrieve. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Agent: + An agent acts as the fundamental + building block that provides + instructions to the Large Language Model + (LLM) for executing specific tasks. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.GetAgentRequest): + request = agent_service.GetAgentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_agent] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_agent( + self, + request: Optional[Union[agent_service.CreateAgentRequest, dict]] = None, + *, + parent: Optional[str] = None, + agent: Optional[gcc_agent.Agent] = None, + agent_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_agent.Agent: + r"""Creates a new agent in the given app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_create_agent(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + agent = ces_v1beta.Agent() + agent.display_name = "display_name_value" + + request = ces_v1beta.CreateAgentRequest( + parent="parent_value", + agent=agent, + ) + + # Make the request + response = client.create_agent(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.CreateAgentRequest, dict]): + The request object. Request message for + [AgentService.CreateAgent][google.cloud.ces.v1beta.AgentService.CreateAgent]. + parent (str): + Required. The resource name of the + app to create an agent in. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + agent (google.cloud.ces_v1beta.types.Agent): + Required. The agent to create. + This corresponds to the ``agent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + agent_id (str): + Optional. The ID to use for the + agent, which will become the final + component of the agent's resource name. + If not provided, a unique ID will be + automatically assigned for the agent. + + This corresponds to the ``agent_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Agent: + An agent acts as the fundamental + building block that provides + instructions to the Large Language Model + (LLM) for executing specific tasks. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, agent, agent_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.CreateAgentRequest): + request = agent_service.CreateAgentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if agent is not None: + request.agent = agent + if agent_id is not None: + request.agent_id = agent_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_agent] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_agent( + self, + request: Optional[Union[agent_service.UpdateAgentRequest, dict]] = None, + *, + agent: Optional[gcc_agent.Agent] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_agent.Agent: + r"""Updates the specified agent. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_update_agent(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + agent = ces_v1beta.Agent() + agent.display_name = "display_name_value" + + request = ces_v1beta.UpdateAgentRequest( + agent=agent, + ) + + # Make the request + response = client.update_agent(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.UpdateAgentRequest, dict]): + The request object. Request message for + [AgentService.UpdateAgent][google.cloud.ces.v1beta.AgentService.UpdateAgent]. + agent (google.cloud.ces_v1beta.types.Agent): + Required. The agent to update. + This corresponds to the ``agent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to + control which fields get updated. If the + mask is not present, all fields will be + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Agent: + An agent acts as the fundamental + building block that provides + instructions to the Large Language Model + (LLM) for executing specific tasks. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [agent, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.UpdateAgentRequest): + request = agent_service.UpdateAgentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if agent is not None: + request.agent = agent + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_agent] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("agent.name", request.agent.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_agent( + self, + request: Optional[Union[agent_service.DeleteAgentRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the specified agent. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_delete_agent(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteAgentRequest( + name="name_value", + ) + + # Make the request + client.delete_agent(request=request) + + Args: + request (Union[google.cloud.ces_v1beta.types.DeleteAgentRequest, dict]): + The request object. Request message for + [AgentService.DeleteAgent][google.cloud.ces.v1beta.AgentService.DeleteAgent]. + name (str): + Required. The resource name of the + agent to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.DeleteAgentRequest): + request = agent_service.DeleteAgentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_agent] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_examples( + self, + request: Optional[Union[agent_service.ListExamplesRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListExamplesPager: + r"""Lists examples in the given app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_list_examples(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ListExamplesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_examples(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.ListExamplesRequest, dict]): + The request object. Request message for + [AgentService.ListExamples][google.cloud.ces.v1beta.AgentService.ListExamples]. + parent (str): + Required. The resource name of the + app to list examples from. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.services.agent_service.pagers.ListExamplesPager: + Response message for + [AgentService.ListExamples][google.cloud.ces.v1beta.AgentService.ListExamples]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.ListExamplesRequest): + request = agent_service.ListExamplesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_examples] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListExamplesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_example( + self, + request: Optional[Union[agent_service.GetExampleRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> example.Example: + r"""Gets details of the specified example. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_get_example(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.GetExampleRequest( + name="name_value", + ) + + # Make the request + response = client.get_example(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.GetExampleRequest, dict]): + The request object. Request message for + [AgentService.GetExample][google.cloud.ces.v1beta.AgentService.GetExample]. + name (str): + Required. The resource name of the + example to retrieve. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Example: + An example represents a sample + conversation between the user and the + agent(s). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.GetExampleRequest): + request = agent_service.GetExampleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_example] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_example( + self, + request: Optional[Union[agent_service.CreateExampleRequest, dict]] = None, + *, + parent: Optional[str] = None, + example: Optional[gcc_example.Example] = None, + example_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_example.Example: + r"""Creates a new example in the given app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_create_example(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + example = ces_v1beta.Example() + example.display_name = "display_name_value" + + request = ces_v1beta.CreateExampleRequest( + parent="parent_value", + example=example, + ) + + # Make the request + response = client.create_example(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.CreateExampleRequest, dict]): + The request object. Request message for + [AgentService.CreateExample][google.cloud.ces.v1beta.AgentService.CreateExample]. + parent (str): + Required. The resource name of the + app to create an example in. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + example (google.cloud.ces_v1beta.types.Example): + Required. The example to create. + This corresponds to the ``example`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + example_id (str): + Optional. The ID to use for the + example, which will become the final + component of the example's resource + name. If not provided, a unique ID will + be automatically assigned for the + example. + + This corresponds to the ``example_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Example: + An example represents a sample + conversation between the user and the + agent(s). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, example, example_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.CreateExampleRequest): + request = agent_service.CreateExampleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if example is not None: + request.example = example + if example_id is not None: + request.example_id = example_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_example] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_example( + self, + request: Optional[Union[agent_service.UpdateExampleRequest, dict]] = None, + *, + example: Optional[gcc_example.Example] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_example.Example: + r"""Updates the specified example. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_update_example(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + example = ces_v1beta.Example() + example.display_name = "display_name_value" + + request = ces_v1beta.UpdateExampleRequest( + example=example, + ) + + # Make the request + response = client.update_example(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.UpdateExampleRequest, dict]): + The request object. Request message for + [AgentService.UpdateExample][google.cloud.ces.v1beta.AgentService.UpdateExample]. + example (google.cloud.ces_v1beta.types.Example): + Required. The example to update. + This corresponds to the ``example`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to + control which fields get updated. If the + mask is not present, all fields will be + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Example: + An example represents a sample + conversation between the user and the + agent(s). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [example, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.UpdateExampleRequest): + request = agent_service.UpdateExampleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if example is not None: + request.example = example + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_example] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("example.name", request.example.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_example( + self, + request: Optional[Union[agent_service.DeleteExampleRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the specified example. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_delete_example(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteExampleRequest( + name="name_value", + ) + + # Make the request + client.delete_example(request=request) + + Args: + request (Union[google.cloud.ces_v1beta.types.DeleteExampleRequest, dict]): + The request object. Request message for + [AgentService.DeleteExample][google.cloud.ces.v1beta.AgentService.DeleteExample]. + name (str): + Required. The resource name of the + example to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.DeleteExampleRequest): + request = agent_service.DeleteExampleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_example] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_tools( + self, + request: Optional[Union[agent_service.ListToolsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListToolsPager: + r"""Lists tools in the given app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_list_tools(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ListToolsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_tools(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.ListToolsRequest, dict]): + The request object. Request message for + [AgentService.ListTools][google.cloud.ces.v1beta.AgentService.ListTools]. + parent (str): + Required. The resource name of the + app to list tools from. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.services.agent_service.pagers.ListToolsPager: + Response message for + [AgentService.ListTools][google.cloud.ces.v1beta.AgentService.ListTools]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.ListToolsRequest): + request = agent_service.ListToolsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_tools] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListToolsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_tool( + self, + request: Optional[Union[agent_service.GetToolRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> tool.Tool: + r"""Gets details of the specified tool. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_get_tool(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.GetToolRequest( + name="name_value", + ) + + # Make the request + response = client.get_tool(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.GetToolRequest, dict]): + The request object. Request message for + [AgentService.GetTool][google.cloud.ces.v1beta.AgentService.GetTool]. + name (str): + Required. The resource name of the + tool to retrieve. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Tool: + A tool represents an action that the + CES agent can take to achieve certain + goals. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.GetToolRequest): + request = agent_service.GetToolRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_tool] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_conversations( + self, + request: Optional[Union[agent_service.ListConversationsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListConversationsPager: + r"""Lists conversations in the given app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_list_conversations(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ListConversationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_conversations(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.ListConversationsRequest, dict]): + The request object. Request message for + [AgentService.ListConversations][google.cloud.ces.v1beta.AgentService.ListConversations]. + parent (str): + Required. The resource name of the + app to list conversations from. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.services.agent_service.pagers.ListConversationsPager: + Response message for + [AgentService.ListConversations][google.cloud.ces.v1beta.AgentService.ListConversations]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.ListConversationsRequest): + request = agent_service.ListConversationsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_conversations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListConversationsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_conversation( + self, + request: Optional[Union[agent_service.GetConversationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> conversation.Conversation: + r"""Gets details of the specified conversation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_get_conversation(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.GetConversationRequest( + name="name_value", + ) + + # Make the request + response = client.get_conversation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.GetConversationRequest, dict]): + The request object. Request message for + [AgentService.GetConversation][google.cloud.ces.v1beta.AgentService.GetConversation]. + name (str): + Required. The resource name of the + conversation to retrieve. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Conversation: + A conversation represents an + interaction between an end user and the + CES app. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.GetConversationRequest): + request = agent_service.GetConversationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_conversation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_conversation( + self, + request: Optional[Union[agent_service.DeleteConversationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the specified conversation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_delete_conversation(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteConversationRequest( + name="name_value", + ) + + # Make the request + client.delete_conversation(request=request) + + Args: + request (Union[google.cloud.ces_v1beta.types.DeleteConversationRequest, dict]): + The request object. Request message for + [AgentService.DeleteConversation][google.cloud.ces.v1beta.AgentService.DeleteConversation]. + name (str): + Required. The resource name of the + conversation to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.DeleteConversationRequest): + request = agent_service.DeleteConversationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_conversation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def batch_delete_conversations( + self, + request: Optional[ + Union[agent_service.BatchDeleteConversationsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Batch deletes the specified conversations. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_batch_delete_conversations(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.BatchDeleteConversationsRequest( + parent="parent_value", + conversations=['conversations_value1', 'conversations_value2'], + ) + + # Make the request + operation = client.batch_delete_conversations(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.BatchDeleteConversationsRequest, dict]): + The request object. Request message for + [AgentService.BatchDeleteConversations][google.cloud.ces.v1beta.AgentService.BatchDeleteConversations]. + parent (str): + Required. The resource name of the app to delete + conversations from. Format: + ``projects/{project}/locations/{location}/apps/{app}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.ces_v1beta.types.BatchDeleteConversationsResponse` Response message for + [AgentService.BatchDeleteConversations][google.cloud.ces.v1beta.AgentService.BatchDeleteConversations]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.BatchDeleteConversationsRequest): + request = agent_service.BatchDeleteConversationsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.batch_delete_conversations + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + agent_service.BatchDeleteConversationsResponse, + metadata_type=agent_service.OperationMetadata, + ) + + # Done; return the response. + return response + + def create_tool( + self, + request: Optional[Union[agent_service.CreateToolRequest, dict]] = None, + *, + parent: Optional[str] = None, + tool: Optional[gcc_tool.Tool] = None, + tool_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_tool.Tool: + r"""Creates a new tool in the given app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_create_tool(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + tool = ces_v1beta.Tool() + tool.client_function.name = "name_value" + + request = ces_v1beta.CreateToolRequest( + parent="parent_value", + tool=tool, + ) + + # Make the request + response = client.create_tool(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.CreateToolRequest, dict]): + The request object. Request message for + [AgentService.CreateTool][google.cloud.ces.v1beta.AgentService.CreateTool]. + parent (str): + Required. The resource name of the + app to create a tool in. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tool (google.cloud.ces_v1beta.types.Tool): + Required. The tool to create. + This corresponds to the ``tool`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tool_id (str): + Optional. The ID to use for the tool, + which will become the final component of + the tool's resource name. If not + provided, a unique ID will be + automatically assigned for the tool. + + This corresponds to the ``tool_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Tool: + A tool represents an action that the + CES agent can take to achieve certain + goals. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, tool, tool_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.CreateToolRequest): + request = agent_service.CreateToolRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if tool is not None: + request.tool = tool + if tool_id is not None: + request.tool_id = tool_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_tool] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_tool( + self, + request: Optional[Union[agent_service.UpdateToolRequest, dict]] = None, + *, + tool: Optional[gcc_tool.Tool] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_tool.Tool: + r"""Updates the specified tool. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_update_tool(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + tool = ces_v1beta.Tool() + tool.client_function.name = "name_value" + + request = ces_v1beta.UpdateToolRequest( + tool=tool, + ) + + # Make the request + response = client.update_tool(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.UpdateToolRequest, dict]): + The request object. Request message for + [AgentService.UpdateTool][google.cloud.ces.v1beta.AgentService.UpdateTool]. + tool (google.cloud.ces_v1beta.types.Tool): + Required. The tool to update. + This corresponds to the ``tool`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to + control which fields get updated. If the + mask is not present, all fields will be + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Tool: + A tool represents an action that the + CES agent can take to achieve certain + goals. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [tool, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.UpdateToolRequest): + request = agent_service.UpdateToolRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if tool is not None: + request.tool = tool + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_tool] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("tool.name", request.tool.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_tool( + self, + request: Optional[Union[agent_service.DeleteToolRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the specified tool. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_delete_tool(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteToolRequest( + name="name_value", + ) + + # Make the request + client.delete_tool(request=request) + + Args: + request (Union[google.cloud.ces_v1beta.types.DeleteToolRequest, dict]): + The request object. Request message for + [AgentService.DeleteTool][google.cloud.ces.v1beta.AgentService.DeleteTool]. + name (str): + Required. The resource name of the + tool to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.DeleteToolRequest): + request = agent_service.DeleteToolRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_tool] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_guardrails( + self, + request: Optional[Union[agent_service.ListGuardrailsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListGuardrailsPager: + r"""Lists guardrails in the given app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_list_guardrails(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ListGuardrailsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_guardrails(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.ListGuardrailsRequest, dict]): + The request object. Request message for + [AgentService.ListGuardrails][google.cloud.ces.v1beta.AgentService.ListGuardrails]. + parent (str): + Required. The resource name of the + app to list guardrails from. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.services.agent_service.pagers.ListGuardrailsPager: + Response message for + [AgentService.ListGuardrails][google.cloud.ces.v1beta.AgentService.ListGuardrails]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.ListGuardrailsRequest): + request = agent_service.ListGuardrailsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_guardrails] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListGuardrailsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_guardrail( + self, + request: Optional[Union[agent_service.GetGuardrailRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> guardrail.Guardrail: + r"""Gets details of the specified guardrail. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_get_guardrail(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.GetGuardrailRequest( + name="name_value", + ) + + # Make the request + response = client.get_guardrail(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.GetGuardrailRequest, dict]): + The request object. Request message for + [AgentService.GetGuardrail][google.cloud.ces.v1beta.AgentService.GetGuardrail]. + name (str): + Required. The resource name of the + guardrail to retrieve. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Guardrail: + Guardrail contains a list of checks + and balances to keep the agents safe and + secure. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.GetGuardrailRequest): + request = agent_service.GetGuardrailRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_guardrail] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_guardrail( + self, + request: Optional[Union[agent_service.CreateGuardrailRequest, dict]] = None, + *, + parent: Optional[str] = None, + guardrail: Optional[gcc_guardrail.Guardrail] = None, + guardrail_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_guardrail.Guardrail: + r"""Creates a new guardrail in the given app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_create_guardrail(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + guardrail = ces_v1beta.Guardrail() + guardrail.content_filter.match_type = "REGEXP_MATCH" + guardrail.display_name = "display_name_value" + + request = ces_v1beta.CreateGuardrailRequest( + parent="parent_value", + guardrail=guardrail, + ) + + # Make the request + response = client.create_guardrail(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.CreateGuardrailRequest, dict]): + The request object. Request message for + [AgentService.CreateGuardrail][google.cloud.ces.v1beta.AgentService.CreateGuardrail]. + parent (str): + Required. The resource name of the + app to create a guardrail in. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + guardrail (google.cloud.ces_v1beta.types.Guardrail): + Required. The guardrail to create. + This corresponds to the ``guardrail`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + guardrail_id (str): + Optional. The ID to use for the + guardrail, which will become the final + component of the guardrail's resource + name. If not provided, a unique ID will + be automatically assigned for the + guardrail. + + This corresponds to the ``guardrail_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Guardrail: + Guardrail contains a list of checks + and balances to keep the agents safe and + secure. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, guardrail, guardrail_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.CreateGuardrailRequest): + request = agent_service.CreateGuardrailRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if guardrail is not None: + request.guardrail = guardrail + if guardrail_id is not None: + request.guardrail_id = guardrail_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_guardrail] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_guardrail( + self, + request: Optional[Union[agent_service.UpdateGuardrailRequest, dict]] = None, + *, + guardrail: Optional[gcc_guardrail.Guardrail] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_guardrail.Guardrail: + r"""Updates the specified guardrail. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_update_guardrail(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + guardrail = ces_v1beta.Guardrail() + guardrail.content_filter.match_type = "REGEXP_MATCH" + guardrail.display_name = "display_name_value" + + request = ces_v1beta.UpdateGuardrailRequest( + guardrail=guardrail, + ) + + # Make the request + response = client.update_guardrail(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.UpdateGuardrailRequest, dict]): + The request object. Request message for + [AgentService.UpdateGuardrail][google.cloud.ces.v1beta.AgentService.UpdateGuardrail]. + guardrail (google.cloud.ces_v1beta.types.Guardrail): + Required. The guardrail to update. + This corresponds to the ``guardrail`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to + control which fields get updated. If the + mask is not present, all fields will be + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Guardrail: + Guardrail contains a list of checks + and balances to keep the agents safe and + secure. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [guardrail, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.UpdateGuardrailRequest): + request = agent_service.UpdateGuardrailRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if guardrail is not None: + request.guardrail = guardrail + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_guardrail] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("guardrail.name", request.guardrail.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_guardrail( + self, + request: Optional[Union[agent_service.DeleteGuardrailRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the specified guardrail. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_delete_guardrail(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteGuardrailRequest( + name="name_value", + ) + + # Make the request + client.delete_guardrail(request=request) + + Args: + request (Union[google.cloud.ces_v1beta.types.DeleteGuardrailRequest, dict]): + The request object. Request message for + [AgentService.DeleteGuardrail][google.cloud.ces.v1beta.AgentService.DeleteGuardrail]. + name (str): + Required. The resource name of the + guardrail to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.DeleteGuardrailRequest): + request = agent_service.DeleteGuardrailRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_guardrail] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_deployments( + self, + request: Optional[Union[agent_service.ListDeploymentsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListDeploymentsPager: + r"""Lists deployments in the given app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_list_deployments(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ListDeploymentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_deployments(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.ListDeploymentsRequest, dict]): + The request object. Request message for + [AgentService.ListDeployments][google.cloud.ces.v1beta.AgentService.ListDeployments]. + parent (str): + Required. The parent app. Format: + ``projects/{project}/locations/{location}/apps/{app}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.services.agent_service.pagers.ListDeploymentsPager: + Response message for + [AgentService.ListDeployments][google.cloud.ces.v1beta.AgentService.ListDeployments]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.ListDeploymentsRequest): + request = agent_service.ListDeploymentsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_deployments] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListDeploymentsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_deployment( + self, + request: Optional[Union[agent_service.GetDeploymentRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> deployment.Deployment: + r"""Gets details of the specified deployment. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_get_deployment(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.GetDeploymentRequest( + name="name_value", + ) + + # Make the request + response = client.get_deployment(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.GetDeploymentRequest, dict]): + The request object. Request message for + [AgentService.GetDeployment][google.cloud.ces.v1beta.AgentService.GetDeployment]. + name (str): + Required. The name of the deployment. Format: + ``projects/{project}/locations/{location}/apps/{app}/deployments/{deployment}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Deployment: + A deployment represents an immutable, + queryable version of the app. It is used + to deploy an app version with a specific + channel profile. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.GetDeploymentRequest): + request = agent_service.GetDeploymentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_deployment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_deployment( + self, + request: Optional[Union[agent_service.CreateDeploymentRequest, dict]] = None, + *, + parent: Optional[str] = None, + deployment: Optional[gcc_deployment.Deployment] = None, + deployment_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_deployment.Deployment: + r"""Creates a new deployment in the given app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_create_deployment(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + deployment = ces_v1beta.Deployment() + deployment.display_name = "display_name_value" + + request = ces_v1beta.CreateDeploymentRequest( + parent="parent_value", + deployment=deployment, + ) + + # Make the request + response = client.create_deployment(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.CreateDeploymentRequest, dict]): + The request object. Request message for + [AgentService.CreateDeployment][google.cloud.ces.v1beta.AgentService.CreateDeployment]. + parent (str): + Required. The parent app. Format: + ``projects/{project}/locations/{location}/apps/{app}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + deployment (google.cloud.ces_v1beta.types.Deployment): + Required. The deployment to create. + This corresponds to the ``deployment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + deployment_id (str): + Optional. The ID to use for the + deployment, which will become the final + component of the deployment's resource + name. If not provided, a unique ID will + be automatically assigned for the + deployment. + + This corresponds to the ``deployment_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Deployment: + A deployment represents an immutable, + queryable version of the app. It is used + to deploy an app version with a specific + channel profile. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, deployment, deployment_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.CreateDeploymentRequest): + request = agent_service.CreateDeploymentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if deployment is not None: + request.deployment = deployment + if deployment_id is not None: + request.deployment_id = deployment_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_deployment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_deployment( + self, + request: Optional[Union[agent_service.UpdateDeploymentRequest, dict]] = None, + *, + deployment: Optional[gcc_deployment.Deployment] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_deployment.Deployment: + r"""Updates the specified deployment. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_update_deployment(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + deployment = ces_v1beta.Deployment() + deployment.display_name = "display_name_value" + + request = ces_v1beta.UpdateDeploymentRequest( + deployment=deployment, + ) + + # Make the request + response = client.update_deployment(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.UpdateDeploymentRequest, dict]): + The request object. Request message for + [AgentService.UpdateDeployment][google.cloud.ces.v1beta.AgentService.UpdateDeployment]. + deployment (google.cloud.ces_v1beta.types.Deployment): + Required. The deployment to update. + This corresponds to the ``deployment`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to + update. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Deployment: + A deployment represents an immutable, + queryable version of the app. It is used + to deploy an app version with a specific + channel profile. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [deployment, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.UpdateDeploymentRequest): + request = agent_service.UpdateDeploymentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if deployment is not None: + request.deployment = deployment + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_deployment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("deployment.name", request.deployment.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_deployment( + self, + request: Optional[Union[agent_service.DeleteDeploymentRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the specified deployment. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_delete_deployment(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteDeploymentRequest( + name="name_value", + ) + + # Make the request + client.delete_deployment(request=request) + + Args: + request (Union[google.cloud.ces_v1beta.types.DeleteDeploymentRequest, dict]): + The request object. Request message for + [AgentService.DeleteDeployment][google.cloud.ces.v1beta.AgentService.DeleteDeployment]. + name (str): + Required. The name of the deployment to delete. Format: + ``projects/{project}/locations/{location}/apps/{app}/deployments/{deployment}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.DeleteDeploymentRequest): + request = agent_service.DeleteDeploymentRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_deployment] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_toolsets( + self, + request: Optional[Union[agent_service.ListToolsetsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListToolsetsPager: + r"""Lists toolsets in the given app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_list_toolsets(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ListToolsetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_toolsets(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.ListToolsetsRequest, dict]): + The request object. Request message for + [AgentService.ListToolsets][google.cloud.ces.v1beta.AgentService.ListToolsets]. + parent (str): + Required. The resource name of the + app to list toolsets from. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.services.agent_service.pagers.ListToolsetsPager: + Response message for + [AgentService.ListToolsets][google.cloud.ces.v1beta.AgentService.ListToolsets]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.ListToolsetsRequest): + request = agent_service.ListToolsetsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_toolsets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListToolsetsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_toolset( + self, + request: Optional[Union[agent_service.GetToolsetRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> toolset.Toolset: + r"""Gets details of the specified toolset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_get_toolset(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.GetToolsetRequest( + name="name_value", + ) + + # Make the request + response = client.get_toolset(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.GetToolsetRequest, dict]): + The request object. Request message for + [AgentService.GetToolset][google.cloud.ces.v1beta.AgentService.GetToolset]. + name (str): + Required. The resource name of the + toolset to retrieve. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Toolset: + A toolset represents a group of + dynamically managed tools that can be + used by the agent. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.GetToolsetRequest): + request = agent_service.GetToolsetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_toolset] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_toolset( + self, + request: Optional[Union[agent_service.CreateToolsetRequest, dict]] = None, + *, + parent: Optional[str] = None, + toolset: Optional[gcc_toolset.Toolset] = None, + toolset_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_toolset.Toolset: + r"""Creates a new toolset in the given app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_create_toolset(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + toolset = ces_v1beta.Toolset() + toolset.mcp_toolset.server_address = "server_address_value" + + request = ces_v1beta.CreateToolsetRequest( + parent="parent_value", + toolset=toolset, + ) + + # Make the request + response = client.create_toolset(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.CreateToolsetRequest, dict]): + The request object. Request message for + [AgentService.CreateToolset][google.cloud.ces.v1beta.AgentService.CreateToolset]. + parent (str): + Required. The resource name of the + app to create a toolset in. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + toolset (google.cloud.ces_v1beta.types.Toolset): + Required. The toolset to create. + This corresponds to the ``toolset`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + toolset_id (str): + Optional. The ID to use for the + toolset, which will become the final + component of the toolset's resource + name. If not provided, a unique ID will + be automatically assigned for the + toolset. + + This corresponds to the ``toolset_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Toolset: + A toolset represents a group of + dynamically managed tools that can be + used by the agent. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, toolset, toolset_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.CreateToolsetRequest): + request = agent_service.CreateToolsetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if toolset is not None: + request.toolset = toolset + if toolset_id is not None: + request.toolset_id = toolset_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_toolset] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_toolset( + self, + request: Optional[Union[agent_service.UpdateToolsetRequest, dict]] = None, + *, + toolset: Optional[gcc_toolset.Toolset] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_toolset.Toolset: + r"""Updates the specified toolset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_update_toolset(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + toolset = ces_v1beta.Toolset() + toolset.mcp_toolset.server_address = "server_address_value" + + request = ces_v1beta.UpdateToolsetRequest( + toolset=toolset, + ) + + # Make the request + response = client.update_toolset(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.UpdateToolsetRequest, dict]): + The request object. Request message for + [AgentService.UpdateToolset][google.cloud.ces.v1beta.AgentService.UpdateToolset]. + toolset (google.cloud.ces_v1beta.types.Toolset): + Required. The toolset to update. + This corresponds to the ``toolset`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to + control which fields get updated. If the + mask is not present, all fields will be + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Toolset: + A toolset represents a group of + dynamically managed tools that can be + used by the agent. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [toolset, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.UpdateToolsetRequest): + request = agent_service.UpdateToolsetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if toolset is not None: + request.toolset = toolset + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_toolset] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("toolset.name", request.toolset.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_toolset( + self, + request: Optional[Union[agent_service.DeleteToolsetRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the specified toolset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_delete_toolset(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteToolsetRequest( + name="name_value", + ) + + # Make the request + client.delete_toolset(request=request) + + Args: + request (Union[google.cloud.ces_v1beta.types.DeleteToolsetRequest, dict]): + The request object. Request message for + [AgentService.DeleteToolset][google.cloud.ces.v1beta.AgentService.DeleteToolset]. + name (str): + Required. The resource name of the + toolset to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.DeleteToolsetRequest): + request = agent_service.DeleteToolsetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_toolset] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def list_app_versions( + self, + request: Optional[Union[agent_service.ListAppVersionsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListAppVersionsPager: + r"""Lists all app versions in the given app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_list_app_versions(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ListAppVersionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_app_versions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.ListAppVersionsRequest, dict]): + The request object. Request message for + [AgentService.ListAppVersions][google.cloud.ces.v1beta.AgentService.ListAppVersions]. + parent (str): + Required. The resource name of the + app to list app versions from. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.services.agent_service.pagers.ListAppVersionsPager: + Response message for + [AgentService.ListAppVersions][google.cloud.ces.v1beta.AgentService.ListAppVersions]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.ListAppVersionsRequest): + request = agent_service.ListAppVersionsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_app_versions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListAppVersionsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_app_version( + self, + request: Optional[Union[agent_service.GetAppVersionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> app_version.AppVersion: + r"""Gets details of the specified app version. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_get_app_version(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.GetAppVersionRequest( + name="name_value", + ) + + # Make the request + response = client.get_app_version(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.GetAppVersionRequest, dict]): + The request object. Request message for + [AgentService.GetAppVersion][google.cloud.ces.v1beta.AgentService.GetAppVersion]. + name (str): + Required. The resource name of the + app version to retrieve. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.AppVersion: + In Customer Engagement Suite (CES), + an app version is a snapshot of the app + at a specific point in time. It is + immutable and cannot be modified once + created. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.GetAppVersionRequest): + request = agent_service.GetAppVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_app_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_app_version( + self, + request: Optional[Union[agent_service.CreateAppVersionRequest, dict]] = None, + *, + parent: Optional[str] = None, + app_version: Optional[gcc_app_version.AppVersion] = None, + app_version_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_app_version.AppVersion: + r"""Creates a new app version in the given app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_create_app_version(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.CreateAppVersionRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_app_version(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.CreateAppVersionRequest, dict]): + The request object. Request message for + [AgentService.CreateAppVersion][google.cloud.ces.v1beta.AgentService.CreateAppVersion] + parent (str): + Required. The resource name of the + app to create an app version in. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + app_version (google.cloud.ces_v1beta.types.AppVersion): + Required. The app version to create. + This corresponds to the ``app_version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + app_version_id (str): + Optional. The ID to use for the app + version, which will become the final + component of the app version's resource + name. If not provided, a unique ID will + be automatically assigned for the app + version. + + This corresponds to the ``app_version_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.AppVersion: + In Customer Engagement Suite (CES), + an app version is a snapshot of the app + at a specific point in time. It is + immutable and cannot be modified once + created. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, app_version, app_version_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.CreateAppVersionRequest): + request = agent_service.CreateAppVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if app_version is not None: + request.app_version = app_version + if app_version_id is not None: + request.app_version_id = app_version_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_app_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_app_version( + self, + request: Optional[Union[agent_service.DeleteAppVersionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the specified app version. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_delete_app_version(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteAppVersionRequest( + name="name_value", + ) + + # Make the request + client.delete_app_version(request=request) + + Args: + request (Union[google.cloud.ces_v1beta.types.DeleteAppVersionRequest, dict]): + The request object. Request message for + [AgentService.DeleteAppVersion][google.cloud.ces.v1beta.AgentService.DeleteAppVersion]. + name (str): + Required. The resource name of the + app version to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.DeleteAppVersionRequest): + request = agent_service.DeleteAppVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_app_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def restore_app_version( + self, + request: Optional[Union[agent_service.RestoreAppVersionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Restores the specified app version. + This will create a new app version from the current + draft app and overwrite the current draft with the + specified app version. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_restore_app_version(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.RestoreAppVersionRequest( + name="name_value", + ) + + # Make the request + operation = client.restore_app_version(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.RestoreAppVersionRequest, dict]): + The request object. Request message for + [AgentService.RestoreAppVersion][google.cloud.ces.v1beta.AgentService.RestoreAppVersion] + name (str): + Required. The resource name of the + app version to restore. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.ces_v1beta.types.RestoreAppVersionResponse` Response message for + [AgentService.RestoreAppVersion][google.cloud.ces.v1beta.AgentService.RestoreAppVersion] + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.RestoreAppVersionRequest): + request = agent_service.RestoreAppVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.restore_app_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + agent_service.RestoreAppVersionResponse, + metadata_type=agent_service.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_changelogs( + self, + request: Optional[Union[agent_service.ListChangelogsRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListChangelogsPager: + r"""Lists the changelogs of the specified app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_list_changelogs(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ListChangelogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_changelogs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.ListChangelogsRequest, dict]): + The request object. Request message for + [AgentService.ListChangelogs][google.cloud.ces.v1beta.AgentService.ListChangelogs]. + parent (str): + Required. The resource name of the + app to list changelogs from. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.services.agent_service.pagers.ListChangelogsPager: + Response message for + [AgentService.ListChangelogs][google.cloud.ces.v1beta.AgentService.ListChangelogs]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.ListChangelogsRequest): + request = agent_service.ListChangelogsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_changelogs] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListChangelogsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_changelog( + self, + request: Optional[Union[agent_service.GetChangelogRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> changelog.Changelog: + r"""Gets the specified changelog. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_get_changelog(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.GetChangelogRequest( + name="name_value", + ) + + # Make the request + response = client.get_changelog(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.GetChangelogRequest, dict]): + The request object. Request message for + [AgentService.GetChangelog][google.cloud.ces.v1beta.AgentService.GetChangelog]. + name (str): + Required. The resource name of the + changelog to retrieve. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Changelog: + Changelogs represent a change made to + the app or to an resource within the + app. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, agent_service.GetChangelogRequest): + request = agent_service.GetChangelogRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_changelog] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "AgentServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("AgentServiceClient",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/pagers.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/pagers.py new file mode 100644 index 000000000000..7d95e024f302 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/pagers.py @@ -0,0 +1,1613 @@ +# -*- coding: utf-8 -*- +# 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 typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.cloud.ces_v1beta.types import ( + agent, + agent_service, + app, + app_version, + changelog, + conversation, + deployment, + example, + guardrail, + tool, + toolset, +) + + +class ListAppsPager: + """A pager for iterating through ``list_apps`` requests. + + This class thinly wraps an initial + :class:`google.cloud.ces_v1beta.types.ListAppsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``apps`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListApps`` requests and continue to iterate + through the ``apps`` field on the + corresponding responses. + + All the usual :class:`google.cloud.ces_v1beta.types.ListAppsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., agent_service.ListAppsResponse], + request: agent_service.ListAppsRequest, + response: agent_service.ListAppsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.ces_v1beta.types.ListAppsRequest): + The initial request object. + response (google.cloud.ces_v1beta.types.ListAppsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = agent_service.ListAppsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[agent_service.ListAppsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[app.App]: + for page in self.pages: + yield from page.apps + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListAppsAsyncPager: + """A pager for iterating through ``list_apps`` requests. + + This class thinly wraps an initial + :class:`google.cloud.ces_v1beta.types.ListAppsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``apps`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListApps`` requests and continue to iterate + through the ``apps`` field on the + corresponding responses. + + All the usual :class:`google.cloud.ces_v1beta.types.ListAppsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[agent_service.ListAppsResponse]], + request: agent_service.ListAppsRequest, + response: agent_service.ListAppsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.ces_v1beta.types.ListAppsRequest): + The initial request object. + response (google.cloud.ces_v1beta.types.ListAppsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = agent_service.ListAppsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[agent_service.ListAppsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[app.App]: + async def async_generator(): + async for page in self.pages: + for response in page.apps: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListAgentsPager: + """A pager for iterating through ``list_agents`` requests. + + This class thinly wraps an initial + :class:`google.cloud.ces_v1beta.types.ListAgentsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``agents`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAgents`` requests and continue to iterate + through the ``agents`` field on the + corresponding responses. + + All the usual :class:`google.cloud.ces_v1beta.types.ListAgentsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., agent_service.ListAgentsResponse], + request: agent_service.ListAgentsRequest, + response: agent_service.ListAgentsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.ces_v1beta.types.ListAgentsRequest): + The initial request object. + response (google.cloud.ces_v1beta.types.ListAgentsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = agent_service.ListAgentsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[agent_service.ListAgentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[agent.Agent]: + for page in self.pages: + yield from page.agents + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListAgentsAsyncPager: + """A pager for iterating through ``list_agents`` requests. + + This class thinly wraps an initial + :class:`google.cloud.ces_v1beta.types.ListAgentsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``agents`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAgents`` requests and continue to iterate + through the ``agents`` field on the + corresponding responses. + + All the usual :class:`google.cloud.ces_v1beta.types.ListAgentsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[agent_service.ListAgentsResponse]], + request: agent_service.ListAgentsRequest, + response: agent_service.ListAgentsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.ces_v1beta.types.ListAgentsRequest): + The initial request object. + response (google.cloud.ces_v1beta.types.ListAgentsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = agent_service.ListAgentsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[agent_service.ListAgentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[agent.Agent]: + async def async_generator(): + async for page in self.pages: + for response in page.agents: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListExamplesPager: + """A pager for iterating through ``list_examples`` requests. + + This class thinly wraps an initial + :class:`google.cloud.ces_v1beta.types.ListExamplesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``examples`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListExamples`` requests and continue to iterate + through the ``examples`` field on the + corresponding responses. + + All the usual :class:`google.cloud.ces_v1beta.types.ListExamplesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., agent_service.ListExamplesResponse], + request: agent_service.ListExamplesRequest, + response: agent_service.ListExamplesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.ces_v1beta.types.ListExamplesRequest): + The initial request object. + response (google.cloud.ces_v1beta.types.ListExamplesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = agent_service.ListExamplesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[agent_service.ListExamplesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[example.Example]: + for page in self.pages: + yield from page.examples + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListExamplesAsyncPager: + """A pager for iterating through ``list_examples`` requests. + + This class thinly wraps an initial + :class:`google.cloud.ces_v1beta.types.ListExamplesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``examples`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListExamples`` requests and continue to iterate + through the ``examples`` field on the + corresponding responses. + + All the usual :class:`google.cloud.ces_v1beta.types.ListExamplesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[agent_service.ListExamplesResponse]], + request: agent_service.ListExamplesRequest, + response: agent_service.ListExamplesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.ces_v1beta.types.ListExamplesRequest): + The initial request object. + response (google.cloud.ces_v1beta.types.ListExamplesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = agent_service.ListExamplesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[agent_service.ListExamplesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[example.Example]: + async def async_generator(): + async for page in self.pages: + for response in page.examples: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListToolsPager: + """A pager for iterating through ``list_tools`` requests. + + This class thinly wraps an initial + :class:`google.cloud.ces_v1beta.types.ListToolsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``tools`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListTools`` requests and continue to iterate + through the ``tools`` field on the + corresponding responses. + + All the usual :class:`google.cloud.ces_v1beta.types.ListToolsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., agent_service.ListToolsResponse], + request: agent_service.ListToolsRequest, + response: agent_service.ListToolsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.ces_v1beta.types.ListToolsRequest): + The initial request object. + response (google.cloud.ces_v1beta.types.ListToolsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = agent_service.ListToolsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[agent_service.ListToolsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[tool.Tool]: + for page in self.pages: + yield from page.tools + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListToolsAsyncPager: + """A pager for iterating through ``list_tools`` requests. + + This class thinly wraps an initial + :class:`google.cloud.ces_v1beta.types.ListToolsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``tools`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListTools`` requests and continue to iterate + through the ``tools`` field on the + corresponding responses. + + All the usual :class:`google.cloud.ces_v1beta.types.ListToolsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[agent_service.ListToolsResponse]], + request: agent_service.ListToolsRequest, + response: agent_service.ListToolsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.ces_v1beta.types.ListToolsRequest): + The initial request object. + response (google.cloud.ces_v1beta.types.ListToolsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = agent_service.ListToolsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[agent_service.ListToolsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[tool.Tool]: + async def async_generator(): + async for page in self.pages: + for response in page.tools: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListConversationsPager: + """A pager for iterating through ``list_conversations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.ces_v1beta.types.ListConversationsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``conversations`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListConversations`` requests and continue to iterate + through the ``conversations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.ces_v1beta.types.ListConversationsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., agent_service.ListConversationsResponse], + request: agent_service.ListConversationsRequest, + response: agent_service.ListConversationsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.ces_v1beta.types.ListConversationsRequest): + The initial request object. + response (google.cloud.ces_v1beta.types.ListConversationsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = agent_service.ListConversationsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[agent_service.ListConversationsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[conversation.Conversation]: + for page in self.pages: + yield from page.conversations + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListConversationsAsyncPager: + """A pager for iterating through ``list_conversations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.ces_v1beta.types.ListConversationsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``conversations`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListConversations`` requests and continue to iterate + through the ``conversations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.ces_v1beta.types.ListConversationsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[agent_service.ListConversationsResponse]], + request: agent_service.ListConversationsRequest, + response: agent_service.ListConversationsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.ces_v1beta.types.ListConversationsRequest): + The initial request object. + response (google.cloud.ces_v1beta.types.ListConversationsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = agent_service.ListConversationsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[agent_service.ListConversationsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[conversation.Conversation]: + async def async_generator(): + async for page in self.pages: + for response in page.conversations: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListGuardrailsPager: + """A pager for iterating through ``list_guardrails`` requests. + + This class thinly wraps an initial + :class:`google.cloud.ces_v1beta.types.ListGuardrailsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``guardrails`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListGuardrails`` requests and continue to iterate + through the ``guardrails`` field on the + corresponding responses. + + All the usual :class:`google.cloud.ces_v1beta.types.ListGuardrailsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., agent_service.ListGuardrailsResponse], + request: agent_service.ListGuardrailsRequest, + response: agent_service.ListGuardrailsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.ces_v1beta.types.ListGuardrailsRequest): + The initial request object. + response (google.cloud.ces_v1beta.types.ListGuardrailsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = agent_service.ListGuardrailsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[agent_service.ListGuardrailsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[guardrail.Guardrail]: + for page in self.pages: + yield from page.guardrails + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListGuardrailsAsyncPager: + """A pager for iterating through ``list_guardrails`` requests. + + This class thinly wraps an initial + :class:`google.cloud.ces_v1beta.types.ListGuardrailsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``guardrails`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListGuardrails`` requests and continue to iterate + through the ``guardrails`` field on the + corresponding responses. + + All the usual :class:`google.cloud.ces_v1beta.types.ListGuardrailsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[agent_service.ListGuardrailsResponse]], + request: agent_service.ListGuardrailsRequest, + response: agent_service.ListGuardrailsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.ces_v1beta.types.ListGuardrailsRequest): + The initial request object. + response (google.cloud.ces_v1beta.types.ListGuardrailsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = agent_service.ListGuardrailsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[agent_service.ListGuardrailsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[guardrail.Guardrail]: + async def async_generator(): + async for page in self.pages: + for response in page.guardrails: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListDeploymentsPager: + """A pager for iterating through ``list_deployments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.ces_v1beta.types.ListDeploymentsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``deployments`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDeployments`` requests and continue to iterate + through the ``deployments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.ces_v1beta.types.ListDeploymentsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., agent_service.ListDeploymentsResponse], + request: agent_service.ListDeploymentsRequest, + response: agent_service.ListDeploymentsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.ces_v1beta.types.ListDeploymentsRequest): + The initial request object. + response (google.cloud.ces_v1beta.types.ListDeploymentsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = agent_service.ListDeploymentsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[agent_service.ListDeploymentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[deployment.Deployment]: + for page in self.pages: + yield from page.deployments + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListDeploymentsAsyncPager: + """A pager for iterating through ``list_deployments`` requests. + + This class thinly wraps an initial + :class:`google.cloud.ces_v1beta.types.ListDeploymentsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``deployments`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDeployments`` requests and continue to iterate + through the ``deployments`` field on the + corresponding responses. + + All the usual :class:`google.cloud.ces_v1beta.types.ListDeploymentsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[agent_service.ListDeploymentsResponse]], + request: agent_service.ListDeploymentsRequest, + response: agent_service.ListDeploymentsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.ces_v1beta.types.ListDeploymentsRequest): + The initial request object. + response (google.cloud.ces_v1beta.types.ListDeploymentsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = agent_service.ListDeploymentsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[agent_service.ListDeploymentsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[deployment.Deployment]: + async def async_generator(): + async for page in self.pages: + for response in page.deployments: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListToolsetsPager: + """A pager for iterating through ``list_toolsets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.ces_v1beta.types.ListToolsetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``toolsets`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListToolsets`` requests and continue to iterate + through the ``toolsets`` field on the + corresponding responses. + + All the usual :class:`google.cloud.ces_v1beta.types.ListToolsetsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., agent_service.ListToolsetsResponse], + request: agent_service.ListToolsetsRequest, + response: agent_service.ListToolsetsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.ces_v1beta.types.ListToolsetsRequest): + The initial request object. + response (google.cloud.ces_v1beta.types.ListToolsetsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = agent_service.ListToolsetsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[agent_service.ListToolsetsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[toolset.Toolset]: + for page in self.pages: + yield from page.toolsets + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListToolsetsAsyncPager: + """A pager for iterating through ``list_toolsets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.ces_v1beta.types.ListToolsetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``toolsets`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListToolsets`` requests and continue to iterate + through the ``toolsets`` field on the + corresponding responses. + + All the usual :class:`google.cloud.ces_v1beta.types.ListToolsetsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[agent_service.ListToolsetsResponse]], + request: agent_service.ListToolsetsRequest, + response: agent_service.ListToolsetsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.ces_v1beta.types.ListToolsetsRequest): + The initial request object. + response (google.cloud.ces_v1beta.types.ListToolsetsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = agent_service.ListToolsetsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[agent_service.ListToolsetsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[toolset.Toolset]: + async def async_generator(): + async for page in self.pages: + for response in page.toolsets: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListAppVersionsPager: + """A pager for iterating through ``list_app_versions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.ces_v1beta.types.ListAppVersionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``app_versions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAppVersions`` requests and continue to iterate + through the ``app_versions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.ces_v1beta.types.ListAppVersionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., agent_service.ListAppVersionsResponse], + request: agent_service.ListAppVersionsRequest, + response: agent_service.ListAppVersionsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.ces_v1beta.types.ListAppVersionsRequest): + The initial request object. + response (google.cloud.ces_v1beta.types.ListAppVersionsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = agent_service.ListAppVersionsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[agent_service.ListAppVersionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[app_version.AppVersion]: + for page in self.pages: + yield from page.app_versions + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListAppVersionsAsyncPager: + """A pager for iterating through ``list_app_versions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.ces_v1beta.types.ListAppVersionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``app_versions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAppVersions`` requests and continue to iterate + through the ``app_versions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.ces_v1beta.types.ListAppVersionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[agent_service.ListAppVersionsResponse]], + request: agent_service.ListAppVersionsRequest, + response: agent_service.ListAppVersionsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.ces_v1beta.types.ListAppVersionsRequest): + The initial request object. + response (google.cloud.ces_v1beta.types.ListAppVersionsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = agent_service.ListAppVersionsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[agent_service.ListAppVersionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[app_version.AppVersion]: + async def async_generator(): + async for page in self.pages: + for response in page.app_versions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListChangelogsPager: + """A pager for iterating through ``list_changelogs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.ces_v1beta.types.ListChangelogsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``changelogs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListChangelogs`` requests and continue to iterate + through the ``changelogs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.ces_v1beta.types.ListChangelogsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., agent_service.ListChangelogsResponse], + request: agent_service.ListChangelogsRequest, + response: agent_service.ListChangelogsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.ces_v1beta.types.ListChangelogsRequest): + The initial request object. + response (google.cloud.ces_v1beta.types.ListChangelogsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = agent_service.ListChangelogsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[agent_service.ListChangelogsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[changelog.Changelog]: + for page in self.pages: + yield from page.changelogs + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListChangelogsAsyncPager: + """A pager for iterating through ``list_changelogs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.ces_v1beta.types.ListChangelogsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``changelogs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListChangelogs`` requests and continue to iterate + through the ``changelogs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.ces_v1beta.types.ListChangelogsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[agent_service.ListChangelogsResponse]], + request: agent_service.ListChangelogsRequest, + response: agent_service.ListChangelogsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.ces_v1beta.types.ListChangelogsRequest): + The initial request object. + response (google.cloud.ces_v1beta.types.ListChangelogsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = agent_service.ListChangelogsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[agent_service.ListChangelogsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[changelog.Changelog]: + async def async_generator(): + async for page in self.pages: + for response in page.changelogs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/README.rst b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/README.rst new file mode 100644 index 000000000000..4c0341274edf --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`AgentServiceTransport` is the ABC for all transports. +- public child `AgentServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `AgentServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseAgentServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `AgentServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/__init__.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/__init__.py new file mode 100644 index 000000000000..e516c0a84e54 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# 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 collections import OrderedDict +from typing import Dict, Type + +from .base import AgentServiceTransport +from .grpc import AgentServiceGrpcTransport +from .grpc_asyncio import AgentServiceGrpcAsyncIOTransport +from .rest import AgentServiceRestInterceptor, AgentServiceRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AgentServiceTransport]] +_transport_registry["grpc"] = AgentServiceGrpcTransport +_transport_registry["grpc_asyncio"] = AgentServiceGrpcAsyncIOTransport +_transport_registry["rest"] = AgentServiceRestTransport + +__all__ = ( + "AgentServiceTransport", + "AgentServiceGrpcTransport", + "AgentServiceGrpcAsyncIOTransport", + "AgentServiceRestTransport", + "AgentServiceRestInterceptor", +) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/base.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/base.py new file mode 100644 index 000000000000..a68d57f381c4 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/base.py @@ -0,0 +1,970 @@ +# -*- coding: utf-8 -*- +# 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. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +import google.auth # type: ignore +import google.protobuf +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.ces_v1beta import gapic_version as package_version +from google.cloud.ces_v1beta.types import ( + agent, + agent_service, + app, + app_version, + changelog, + conversation, + deployment, + example, + guardrail, + tool, + toolset, +) +from google.cloud.ces_v1beta.types import agent as gcc_agent +from google.cloud.ces_v1beta.types import app as gcc_app +from google.cloud.ces_v1beta.types import app_version as gcc_app_version +from google.cloud.ces_v1beta.types import deployment as gcc_deployment +from google.cloud.ces_v1beta.types import example as gcc_example +from google.cloud.ces_v1beta.types import guardrail as gcc_guardrail +from google.cloud.ces_v1beta.types import tool as gcc_tool +from google.cloud.ces_v1beta.types import toolset as gcc_toolset + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class AgentServiceTransport(abc.ABC): + """Abstract transport class for AgentService.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/ces", + "https://www.googleapis.com/auth/cloud-platform", + ) + + DEFAULT_HOST: str = "ces.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'ces.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_apps: gapic_v1.method.wrap_method( + self.list_apps, + default_timeout=None, + client_info=client_info, + ), + self.get_app: gapic_v1.method.wrap_method( + self.get_app, + default_timeout=None, + client_info=client_info, + ), + self.create_app: gapic_v1.method.wrap_method( + self.create_app, + default_timeout=None, + client_info=client_info, + ), + self.update_app: gapic_v1.method.wrap_method( + self.update_app, + default_timeout=None, + client_info=client_info, + ), + self.delete_app: gapic_v1.method.wrap_method( + self.delete_app, + default_timeout=None, + client_info=client_info, + ), + self.export_app: gapic_v1.method.wrap_method( + self.export_app, + default_timeout=None, + client_info=client_info, + ), + self.import_app: gapic_v1.method.wrap_method( + self.import_app, + default_timeout=None, + client_info=client_info, + ), + self.list_agents: gapic_v1.method.wrap_method( + self.list_agents, + default_timeout=None, + client_info=client_info, + ), + self.get_agent: gapic_v1.method.wrap_method( + self.get_agent, + default_timeout=None, + client_info=client_info, + ), + self.create_agent: gapic_v1.method.wrap_method( + self.create_agent, + default_timeout=None, + client_info=client_info, + ), + self.update_agent: gapic_v1.method.wrap_method( + self.update_agent, + default_timeout=None, + client_info=client_info, + ), + self.delete_agent: gapic_v1.method.wrap_method( + self.delete_agent, + default_timeout=None, + client_info=client_info, + ), + self.list_examples: gapic_v1.method.wrap_method( + self.list_examples, + default_timeout=None, + client_info=client_info, + ), + self.get_example: gapic_v1.method.wrap_method( + self.get_example, + default_timeout=None, + client_info=client_info, + ), + self.create_example: gapic_v1.method.wrap_method( + self.create_example, + default_timeout=None, + client_info=client_info, + ), + self.update_example: gapic_v1.method.wrap_method( + self.update_example, + default_timeout=None, + client_info=client_info, + ), + self.delete_example: gapic_v1.method.wrap_method( + self.delete_example, + default_timeout=None, + client_info=client_info, + ), + self.list_tools: gapic_v1.method.wrap_method( + self.list_tools, + default_timeout=None, + client_info=client_info, + ), + self.get_tool: gapic_v1.method.wrap_method( + self.get_tool, + default_timeout=None, + client_info=client_info, + ), + self.list_conversations: gapic_v1.method.wrap_method( + self.list_conversations, + default_timeout=None, + client_info=client_info, + ), + self.get_conversation: gapic_v1.method.wrap_method( + self.get_conversation, + default_timeout=None, + client_info=client_info, + ), + self.delete_conversation: gapic_v1.method.wrap_method( + self.delete_conversation, + default_timeout=None, + client_info=client_info, + ), + self.batch_delete_conversations: gapic_v1.method.wrap_method( + self.batch_delete_conversations, + default_timeout=None, + client_info=client_info, + ), + self.create_tool: gapic_v1.method.wrap_method( + self.create_tool, + default_timeout=None, + client_info=client_info, + ), + self.update_tool: gapic_v1.method.wrap_method( + self.update_tool, + default_timeout=None, + client_info=client_info, + ), + self.delete_tool: gapic_v1.method.wrap_method( + self.delete_tool, + default_timeout=None, + client_info=client_info, + ), + self.list_guardrails: gapic_v1.method.wrap_method( + self.list_guardrails, + default_timeout=None, + client_info=client_info, + ), + self.get_guardrail: gapic_v1.method.wrap_method( + self.get_guardrail, + default_timeout=None, + client_info=client_info, + ), + self.create_guardrail: gapic_v1.method.wrap_method( + self.create_guardrail, + default_timeout=None, + client_info=client_info, + ), + self.update_guardrail: gapic_v1.method.wrap_method( + self.update_guardrail, + default_timeout=None, + client_info=client_info, + ), + self.delete_guardrail: gapic_v1.method.wrap_method( + self.delete_guardrail, + default_timeout=None, + client_info=client_info, + ), + self.list_deployments: gapic_v1.method.wrap_method( + self.list_deployments, + default_timeout=None, + client_info=client_info, + ), + self.get_deployment: gapic_v1.method.wrap_method( + self.get_deployment, + default_timeout=None, + client_info=client_info, + ), + self.create_deployment: gapic_v1.method.wrap_method( + self.create_deployment, + default_timeout=None, + client_info=client_info, + ), + self.update_deployment: gapic_v1.method.wrap_method( + self.update_deployment, + default_timeout=None, + client_info=client_info, + ), + self.delete_deployment: gapic_v1.method.wrap_method( + self.delete_deployment, + default_timeout=None, + client_info=client_info, + ), + self.list_toolsets: gapic_v1.method.wrap_method( + self.list_toolsets, + default_timeout=None, + client_info=client_info, + ), + self.get_toolset: gapic_v1.method.wrap_method( + self.get_toolset, + default_timeout=None, + client_info=client_info, + ), + self.create_toolset: gapic_v1.method.wrap_method( + self.create_toolset, + default_timeout=None, + client_info=client_info, + ), + self.update_toolset: gapic_v1.method.wrap_method( + self.update_toolset, + default_timeout=None, + client_info=client_info, + ), + self.delete_toolset: gapic_v1.method.wrap_method( + self.delete_toolset, + default_timeout=None, + client_info=client_info, + ), + self.list_app_versions: gapic_v1.method.wrap_method( + self.list_app_versions, + default_timeout=None, + client_info=client_info, + ), + self.get_app_version: gapic_v1.method.wrap_method( + self.get_app_version, + default_timeout=None, + client_info=client_info, + ), + self.create_app_version: gapic_v1.method.wrap_method( + self.create_app_version, + default_timeout=None, + client_info=client_info, + ), + self.delete_app_version: gapic_v1.method.wrap_method( + self.delete_app_version, + default_timeout=None, + client_info=client_info, + ), + self.restore_app_version: gapic_v1.method.wrap_method( + self.restore_app_version, + default_timeout=None, + client_info=client_info, + ), + self.list_changelogs: gapic_v1.method.wrap_method( + self.list_changelogs, + default_timeout=None, + client_info=client_info, + ), + self.get_changelog: gapic_v1.method.wrap_method( + self.get_changelog, + default_timeout=None, + client_info=client_info, + ), + self.get_location: gapic_v1.method.wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: gapic_v1.method.wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def list_apps( + self, + ) -> Callable[ + [agent_service.ListAppsRequest], + Union[ + agent_service.ListAppsResponse, Awaitable[agent_service.ListAppsResponse] + ], + ]: + raise NotImplementedError() + + @property + def get_app( + self, + ) -> Callable[[agent_service.GetAppRequest], Union[app.App, Awaitable[app.App]]]: + raise NotImplementedError() + + @property + def create_app( + self, + ) -> Callable[ + [agent_service.CreateAppRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def update_app( + self, + ) -> Callable[ + [agent_service.UpdateAppRequest], Union[gcc_app.App, Awaitable[gcc_app.App]] + ]: + raise NotImplementedError() + + @property + def delete_app( + self, + ) -> Callable[ + [agent_service.DeleteAppRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def export_app( + self, + ) -> Callable[ + [agent_service.ExportAppRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def import_app( + self, + ) -> Callable[ + [agent_service.ImportAppRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_agents( + self, + ) -> Callable[ + [agent_service.ListAgentsRequest], + Union[ + agent_service.ListAgentsResponse, + Awaitable[agent_service.ListAgentsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_agent( + self, + ) -> Callable[ + [agent_service.GetAgentRequest], Union[agent.Agent, Awaitable[agent.Agent]] + ]: + raise NotImplementedError() + + @property + def create_agent( + self, + ) -> Callable[ + [agent_service.CreateAgentRequest], + Union[gcc_agent.Agent, Awaitable[gcc_agent.Agent]], + ]: + raise NotImplementedError() + + @property + def update_agent( + self, + ) -> Callable[ + [agent_service.UpdateAgentRequest], + Union[gcc_agent.Agent, Awaitable[gcc_agent.Agent]], + ]: + raise NotImplementedError() + + @property + def delete_agent( + self, + ) -> Callable[ + [agent_service.DeleteAgentRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def list_examples( + self, + ) -> Callable[ + [agent_service.ListExamplesRequest], + Union[ + agent_service.ListExamplesResponse, + Awaitable[agent_service.ListExamplesResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_example( + self, + ) -> Callable[ + [agent_service.GetExampleRequest], + Union[example.Example, Awaitable[example.Example]], + ]: + raise NotImplementedError() + + @property + def create_example( + self, + ) -> Callable[ + [agent_service.CreateExampleRequest], + Union[gcc_example.Example, Awaitable[gcc_example.Example]], + ]: + raise NotImplementedError() + + @property + def update_example( + self, + ) -> Callable[ + [agent_service.UpdateExampleRequest], + Union[gcc_example.Example, Awaitable[gcc_example.Example]], + ]: + raise NotImplementedError() + + @property + def delete_example( + self, + ) -> Callable[ + [agent_service.DeleteExampleRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def list_tools( + self, + ) -> Callable[ + [agent_service.ListToolsRequest], + Union[ + agent_service.ListToolsResponse, Awaitable[agent_service.ListToolsResponse] + ], + ]: + raise NotImplementedError() + + @property + def get_tool( + self, + ) -> Callable[ + [agent_service.GetToolRequest], Union[tool.Tool, Awaitable[tool.Tool]] + ]: + raise NotImplementedError() + + @property + def list_conversations( + self, + ) -> Callable[ + [agent_service.ListConversationsRequest], + Union[ + agent_service.ListConversationsResponse, + Awaitable[agent_service.ListConversationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_conversation( + self, + ) -> Callable[ + [agent_service.GetConversationRequest], + Union[conversation.Conversation, Awaitable[conversation.Conversation]], + ]: + raise NotImplementedError() + + @property + def delete_conversation( + self, + ) -> Callable[ + [agent_service.DeleteConversationRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def batch_delete_conversations( + self, + ) -> Callable[ + [agent_service.BatchDeleteConversationsRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def create_tool( + self, + ) -> Callable[ + [agent_service.CreateToolRequest], + Union[gcc_tool.Tool, Awaitable[gcc_tool.Tool]], + ]: + raise NotImplementedError() + + @property + def update_tool( + self, + ) -> Callable[ + [agent_service.UpdateToolRequest], + Union[gcc_tool.Tool, Awaitable[gcc_tool.Tool]], + ]: + raise NotImplementedError() + + @property + def delete_tool( + self, + ) -> Callable[ + [agent_service.DeleteToolRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def list_guardrails( + self, + ) -> Callable[ + [agent_service.ListGuardrailsRequest], + Union[ + agent_service.ListGuardrailsResponse, + Awaitable[agent_service.ListGuardrailsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_guardrail( + self, + ) -> Callable[ + [agent_service.GetGuardrailRequest], + Union[guardrail.Guardrail, Awaitable[guardrail.Guardrail]], + ]: + raise NotImplementedError() + + @property + def create_guardrail( + self, + ) -> Callable[ + [agent_service.CreateGuardrailRequest], + Union[gcc_guardrail.Guardrail, Awaitable[gcc_guardrail.Guardrail]], + ]: + raise NotImplementedError() + + @property + def update_guardrail( + self, + ) -> Callable[ + [agent_service.UpdateGuardrailRequest], + Union[gcc_guardrail.Guardrail, Awaitable[gcc_guardrail.Guardrail]], + ]: + raise NotImplementedError() + + @property + def delete_guardrail( + self, + ) -> Callable[ + [agent_service.DeleteGuardrailRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def list_deployments( + self, + ) -> Callable[ + [agent_service.ListDeploymentsRequest], + Union[ + agent_service.ListDeploymentsResponse, + Awaitable[agent_service.ListDeploymentsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_deployment( + self, + ) -> Callable[ + [agent_service.GetDeploymentRequest], + Union[deployment.Deployment, Awaitable[deployment.Deployment]], + ]: + raise NotImplementedError() + + @property + def create_deployment( + self, + ) -> Callable[ + [agent_service.CreateDeploymentRequest], + Union[gcc_deployment.Deployment, Awaitable[gcc_deployment.Deployment]], + ]: + raise NotImplementedError() + + @property + def update_deployment( + self, + ) -> Callable[ + [agent_service.UpdateDeploymentRequest], + Union[gcc_deployment.Deployment, Awaitable[gcc_deployment.Deployment]], + ]: + raise NotImplementedError() + + @property + def delete_deployment( + self, + ) -> Callable[ + [agent_service.DeleteDeploymentRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def list_toolsets( + self, + ) -> Callable[ + [agent_service.ListToolsetsRequest], + Union[ + agent_service.ListToolsetsResponse, + Awaitable[agent_service.ListToolsetsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_toolset( + self, + ) -> Callable[ + [agent_service.GetToolsetRequest], + Union[toolset.Toolset, Awaitable[toolset.Toolset]], + ]: + raise NotImplementedError() + + @property + def create_toolset( + self, + ) -> Callable[ + [agent_service.CreateToolsetRequest], + Union[gcc_toolset.Toolset, Awaitable[gcc_toolset.Toolset]], + ]: + raise NotImplementedError() + + @property + def update_toolset( + self, + ) -> Callable[ + [agent_service.UpdateToolsetRequest], + Union[gcc_toolset.Toolset, Awaitable[gcc_toolset.Toolset]], + ]: + raise NotImplementedError() + + @property + def delete_toolset( + self, + ) -> Callable[ + [agent_service.DeleteToolsetRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def list_app_versions( + self, + ) -> Callable[ + [agent_service.ListAppVersionsRequest], + Union[ + agent_service.ListAppVersionsResponse, + Awaitable[agent_service.ListAppVersionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_app_version( + self, + ) -> Callable[ + [agent_service.GetAppVersionRequest], + Union[app_version.AppVersion, Awaitable[app_version.AppVersion]], + ]: + raise NotImplementedError() + + @property + def create_app_version( + self, + ) -> Callable[ + [agent_service.CreateAppVersionRequest], + Union[gcc_app_version.AppVersion, Awaitable[gcc_app_version.AppVersion]], + ]: + raise NotImplementedError() + + @property + def delete_app_version( + self, + ) -> Callable[ + [agent_service.DeleteAppVersionRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def restore_app_version( + self, + ) -> Callable[ + [agent_service.RestoreAppVersionRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_changelogs( + self, + ) -> Callable[ + [agent_service.ListChangelogsRequest], + Union[ + agent_service.ListChangelogsResponse, + Awaitable[agent_service.ListChangelogsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_changelog( + self, + ) -> Callable[ + [agent_service.GetChangelogRequest], + Union[changelog.Changelog, Awaitable[changelog.Changelog]], + ]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def get_location( + self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[ + locations_pb2.ListLocationsResponse, + Awaitable[locations_pb2.ListLocationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("AgentServiceTransport",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/grpc.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/grpc.py new file mode 100644 index 000000000000..0d660609662b --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/grpc.py @@ -0,0 +1,1737 @@ +# -*- coding: utf-8 -*- +# 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. +# +import json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers, operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson + +from google.cloud.ces_v1beta.types import ( + agent, + agent_service, + app, + app_version, + changelog, + conversation, + deployment, + example, + guardrail, + tool, + toolset, +) +from google.cloud.ces_v1beta.types import agent as gcc_agent +from google.cloud.ces_v1beta.types import app as gcc_app +from google.cloud.ces_v1beta.types import app_version as gcc_app_version +from google.cloud.ces_v1beta.types import deployment as gcc_deployment +from google.cloud.ces_v1beta.types import example as gcc_example +from google.cloud.ces_v1beta.types import guardrail as gcc_guardrail +from google.cloud.ces_v1beta.types import tool as gcc_tool +from google.cloud.ces_v1beta.types import toolset as gcc_toolset + +from .base import DEFAULT_CLIENT_INFO, AgentServiceTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class AgentServiceGrpcTransport(AgentServiceTransport): + """gRPC backend transport for AgentService. + + The service that manages agent-related resources in Gemini + Enterprise for Customer Engagement (CES). + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "ces.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'ces.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "ces.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_apps( + self, + ) -> Callable[[agent_service.ListAppsRequest], agent_service.ListAppsResponse]: + r"""Return a callable for the list apps method over gRPC. + + Lists apps in the given project and location. + + Returns: + Callable[[~.ListAppsRequest], + ~.ListAppsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_apps" not in self._stubs: + self._stubs["list_apps"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/ListApps", + request_serializer=agent_service.ListAppsRequest.serialize, + response_deserializer=agent_service.ListAppsResponse.deserialize, + ) + return self._stubs["list_apps"] + + @property + def get_app(self) -> Callable[[agent_service.GetAppRequest], app.App]: + r"""Return a callable for the get app method over gRPC. + + Gets details of the specified app. + + Returns: + Callable[[~.GetAppRequest], + ~.App]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_app" not in self._stubs: + self._stubs["get_app"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/GetApp", + request_serializer=agent_service.GetAppRequest.serialize, + response_deserializer=app.App.deserialize, + ) + return self._stubs["get_app"] + + @property + def create_app( + self, + ) -> Callable[[agent_service.CreateAppRequest], operations_pb2.Operation]: + r"""Return a callable for the create app method over gRPC. + + Creates a new app in the given project and location. + + Returns: + Callable[[~.CreateAppRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_app" not in self._stubs: + self._stubs["create_app"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/CreateApp", + request_serializer=agent_service.CreateAppRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_app"] + + @property + def update_app(self) -> Callable[[agent_service.UpdateAppRequest], gcc_app.App]: + r"""Return a callable for the update app method over gRPC. + + Updates the specified app. + + Returns: + Callable[[~.UpdateAppRequest], + ~.App]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_app" not in self._stubs: + self._stubs["update_app"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/UpdateApp", + request_serializer=agent_service.UpdateAppRequest.serialize, + response_deserializer=gcc_app.App.deserialize, + ) + return self._stubs["update_app"] + + @property + def delete_app( + self, + ) -> Callable[[agent_service.DeleteAppRequest], operations_pb2.Operation]: + r"""Return a callable for the delete app method over gRPC. + + Deletes the specified app. + + Returns: + Callable[[~.DeleteAppRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_app" not in self._stubs: + self._stubs["delete_app"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/DeleteApp", + request_serializer=agent_service.DeleteAppRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_app"] + + @property + def export_app( + self, + ) -> Callable[[agent_service.ExportAppRequest], operations_pb2.Operation]: + r"""Return a callable for the export app method over gRPC. + + Exports the specified app. + + Returns: + Callable[[~.ExportAppRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "export_app" not in self._stubs: + self._stubs["export_app"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/ExportApp", + request_serializer=agent_service.ExportAppRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["export_app"] + + @property + def import_app( + self, + ) -> Callable[[agent_service.ImportAppRequest], operations_pb2.Operation]: + r"""Return a callable for the import app method over gRPC. + + Imports the specified app. + + Returns: + Callable[[~.ImportAppRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "import_app" not in self._stubs: + self._stubs["import_app"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/ImportApp", + request_serializer=agent_service.ImportAppRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["import_app"] + + @property + def list_agents( + self, + ) -> Callable[[agent_service.ListAgentsRequest], agent_service.ListAgentsResponse]: + r"""Return a callable for the list agents method over gRPC. + + Lists agents in the given app. + + Returns: + Callable[[~.ListAgentsRequest], + ~.ListAgentsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_agents" not in self._stubs: + self._stubs["list_agents"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/ListAgents", + request_serializer=agent_service.ListAgentsRequest.serialize, + response_deserializer=agent_service.ListAgentsResponse.deserialize, + ) + return self._stubs["list_agents"] + + @property + def get_agent(self) -> Callable[[agent_service.GetAgentRequest], agent.Agent]: + r"""Return a callable for the get agent method over gRPC. + + Gets details of the specified agent. + + Returns: + Callable[[~.GetAgentRequest], + ~.Agent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_agent" not in self._stubs: + self._stubs["get_agent"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/GetAgent", + request_serializer=agent_service.GetAgentRequest.serialize, + response_deserializer=agent.Agent.deserialize, + ) + return self._stubs["get_agent"] + + @property + def create_agent( + self, + ) -> Callable[[agent_service.CreateAgentRequest], gcc_agent.Agent]: + r"""Return a callable for the create agent method over gRPC. + + Creates a new agent in the given app. + + Returns: + Callable[[~.CreateAgentRequest], + ~.Agent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_agent" not in self._stubs: + self._stubs["create_agent"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/CreateAgent", + request_serializer=agent_service.CreateAgentRequest.serialize, + response_deserializer=gcc_agent.Agent.deserialize, + ) + return self._stubs["create_agent"] + + @property + def update_agent( + self, + ) -> Callable[[agent_service.UpdateAgentRequest], gcc_agent.Agent]: + r"""Return a callable for the update agent method over gRPC. + + Updates the specified agent. + + Returns: + Callable[[~.UpdateAgentRequest], + ~.Agent]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_agent" not in self._stubs: + self._stubs["update_agent"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/UpdateAgent", + request_serializer=agent_service.UpdateAgentRequest.serialize, + response_deserializer=gcc_agent.Agent.deserialize, + ) + return self._stubs["update_agent"] + + @property + def delete_agent( + self, + ) -> Callable[[agent_service.DeleteAgentRequest], empty_pb2.Empty]: + r"""Return a callable for the delete agent method over gRPC. + + Deletes the specified agent. + + Returns: + Callable[[~.DeleteAgentRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_agent" not in self._stubs: + self._stubs["delete_agent"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/DeleteAgent", + request_serializer=agent_service.DeleteAgentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_agent"] + + @property + def list_examples( + self, + ) -> Callable[ + [agent_service.ListExamplesRequest], agent_service.ListExamplesResponse + ]: + r"""Return a callable for the list examples method over gRPC. + + Lists examples in the given app. + + Returns: + Callable[[~.ListExamplesRequest], + ~.ListExamplesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_examples" not in self._stubs: + self._stubs["list_examples"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/ListExamples", + request_serializer=agent_service.ListExamplesRequest.serialize, + response_deserializer=agent_service.ListExamplesResponse.deserialize, + ) + return self._stubs["list_examples"] + + @property + def get_example( + self, + ) -> Callable[[agent_service.GetExampleRequest], example.Example]: + r"""Return a callable for the get example method over gRPC. + + Gets details of the specified example. + + Returns: + Callable[[~.GetExampleRequest], + ~.Example]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_example" not in self._stubs: + self._stubs["get_example"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/GetExample", + request_serializer=agent_service.GetExampleRequest.serialize, + response_deserializer=example.Example.deserialize, + ) + return self._stubs["get_example"] + + @property + def create_example( + self, + ) -> Callable[[agent_service.CreateExampleRequest], gcc_example.Example]: + r"""Return a callable for the create example method over gRPC. + + Creates a new example in the given app. + + Returns: + Callable[[~.CreateExampleRequest], + ~.Example]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_example" not in self._stubs: + self._stubs["create_example"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/CreateExample", + request_serializer=agent_service.CreateExampleRequest.serialize, + response_deserializer=gcc_example.Example.deserialize, + ) + return self._stubs["create_example"] + + @property + def update_example( + self, + ) -> Callable[[agent_service.UpdateExampleRequest], gcc_example.Example]: + r"""Return a callable for the update example method over gRPC. + + Updates the specified example. + + Returns: + Callable[[~.UpdateExampleRequest], + ~.Example]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_example" not in self._stubs: + self._stubs["update_example"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/UpdateExample", + request_serializer=agent_service.UpdateExampleRequest.serialize, + response_deserializer=gcc_example.Example.deserialize, + ) + return self._stubs["update_example"] + + @property + def delete_example( + self, + ) -> Callable[[agent_service.DeleteExampleRequest], empty_pb2.Empty]: + r"""Return a callable for the delete example method over gRPC. + + Deletes the specified example. + + Returns: + Callable[[~.DeleteExampleRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_example" not in self._stubs: + self._stubs["delete_example"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/DeleteExample", + request_serializer=agent_service.DeleteExampleRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_example"] + + @property + def list_tools( + self, + ) -> Callable[[agent_service.ListToolsRequest], agent_service.ListToolsResponse]: + r"""Return a callable for the list tools method over gRPC. + + Lists tools in the given app. + + Returns: + Callable[[~.ListToolsRequest], + ~.ListToolsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_tools" not in self._stubs: + self._stubs["list_tools"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/ListTools", + request_serializer=agent_service.ListToolsRequest.serialize, + response_deserializer=agent_service.ListToolsResponse.deserialize, + ) + return self._stubs["list_tools"] + + @property + def get_tool(self) -> Callable[[agent_service.GetToolRequest], tool.Tool]: + r"""Return a callable for the get tool method over gRPC. + + Gets details of the specified tool. + + Returns: + Callable[[~.GetToolRequest], + ~.Tool]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_tool" not in self._stubs: + self._stubs["get_tool"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/GetTool", + request_serializer=agent_service.GetToolRequest.serialize, + response_deserializer=tool.Tool.deserialize, + ) + return self._stubs["get_tool"] + + @property + def list_conversations( + self, + ) -> Callable[ + [agent_service.ListConversationsRequest], + agent_service.ListConversationsResponse, + ]: + r"""Return a callable for the list conversations method over gRPC. + + Lists conversations in the given app. + + Returns: + Callable[[~.ListConversationsRequest], + ~.ListConversationsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_conversations" not in self._stubs: + self._stubs["list_conversations"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/ListConversations", + request_serializer=agent_service.ListConversationsRequest.serialize, + response_deserializer=agent_service.ListConversationsResponse.deserialize, + ) + return self._stubs["list_conversations"] + + @property + def get_conversation( + self, + ) -> Callable[[agent_service.GetConversationRequest], conversation.Conversation]: + r"""Return a callable for the get conversation method over gRPC. + + Gets details of the specified conversation. + + Returns: + Callable[[~.GetConversationRequest], + ~.Conversation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_conversation" not in self._stubs: + self._stubs["get_conversation"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/GetConversation", + request_serializer=agent_service.GetConversationRequest.serialize, + response_deserializer=conversation.Conversation.deserialize, + ) + return self._stubs["get_conversation"] + + @property + def delete_conversation( + self, + ) -> Callable[[agent_service.DeleteConversationRequest], empty_pb2.Empty]: + r"""Return a callable for the delete conversation method over gRPC. + + Deletes the specified conversation. + + Returns: + Callable[[~.DeleteConversationRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_conversation" not in self._stubs: + self._stubs["delete_conversation"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/DeleteConversation", + request_serializer=agent_service.DeleteConversationRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_conversation"] + + @property + def batch_delete_conversations( + self, + ) -> Callable[ + [agent_service.BatchDeleteConversationsRequest], operations_pb2.Operation + ]: + r"""Return a callable for the batch delete conversations method over gRPC. + + Batch deletes the specified conversations. + + Returns: + Callable[[~.BatchDeleteConversationsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_delete_conversations" not in self._stubs: + self._stubs["batch_delete_conversations"] = ( + self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/BatchDeleteConversations", + request_serializer=agent_service.BatchDeleteConversationsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["batch_delete_conversations"] + + @property + def create_tool(self) -> Callable[[agent_service.CreateToolRequest], gcc_tool.Tool]: + r"""Return a callable for the create tool method over gRPC. + + Creates a new tool in the given app. + + Returns: + Callable[[~.CreateToolRequest], + ~.Tool]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_tool" not in self._stubs: + self._stubs["create_tool"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/CreateTool", + request_serializer=agent_service.CreateToolRequest.serialize, + response_deserializer=gcc_tool.Tool.deserialize, + ) + return self._stubs["create_tool"] + + @property + def update_tool(self) -> Callable[[agent_service.UpdateToolRequest], gcc_tool.Tool]: + r"""Return a callable for the update tool method over gRPC. + + Updates the specified tool. + + Returns: + Callable[[~.UpdateToolRequest], + ~.Tool]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_tool" not in self._stubs: + self._stubs["update_tool"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/UpdateTool", + request_serializer=agent_service.UpdateToolRequest.serialize, + response_deserializer=gcc_tool.Tool.deserialize, + ) + return self._stubs["update_tool"] + + @property + def delete_tool( + self, + ) -> Callable[[agent_service.DeleteToolRequest], empty_pb2.Empty]: + r"""Return a callable for the delete tool method over gRPC. + + Deletes the specified tool. + + Returns: + Callable[[~.DeleteToolRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_tool" not in self._stubs: + self._stubs["delete_tool"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/DeleteTool", + request_serializer=agent_service.DeleteToolRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_tool"] + + @property + def list_guardrails( + self, + ) -> Callable[ + [agent_service.ListGuardrailsRequest], agent_service.ListGuardrailsResponse + ]: + r"""Return a callable for the list guardrails method over gRPC. + + Lists guardrails in the given app. + + Returns: + Callable[[~.ListGuardrailsRequest], + ~.ListGuardrailsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_guardrails" not in self._stubs: + self._stubs["list_guardrails"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/ListGuardrails", + request_serializer=agent_service.ListGuardrailsRequest.serialize, + response_deserializer=agent_service.ListGuardrailsResponse.deserialize, + ) + return self._stubs["list_guardrails"] + + @property + def get_guardrail( + self, + ) -> Callable[[agent_service.GetGuardrailRequest], guardrail.Guardrail]: + r"""Return a callable for the get guardrail method over gRPC. + + Gets details of the specified guardrail. + + Returns: + Callable[[~.GetGuardrailRequest], + ~.Guardrail]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_guardrail" not in self._stubs: + self._stubs["get_guardrail"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/GetGuardrail", + request_serializer=agent_service.GetGuardrailRequest.serialize, + response_deserializer=guardrail.Guardrail.deserialize, + ) + return self._stubs["get_guardrail"] + + @property + def create_guardrail( + self, + ) -> Callable[[agent_service.CreateGuardrailRequest], gcc_guardrail.Guardrail]: + r"""Return a callable for the create guardrail method over gRPC. + + Creates a new guardrail in the given app. + + Returns: + Callable[[~.CreateGuardrailRequest], + ~.Guardrail]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_guardrail" not in self._stubs: + self._stubs["create_guardrail"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/CreateGuardrail", + request_serializer=agent_service.CreateGuardrailRequest.serialize, + response_deserializer=gcc_guardrail.Guardrail.deserialize, + ) + return self._stubs["create_guardrail"] + + @property + def update_guardrail( + self, + ) -> Callable[[agent_service.UpdateGuardrailRequest], gcc_guardrail.Guardrail]: + r"""Return a callable for the update guardrail method over gRPC. + + Updates the specified guardrail. + + Returns: + Callable[[~.UpdateGuardrailRequest], + ~.Guardrail]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_guardrail" not in self._stubs: + self._stubs["update_guardrail"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/UpdateGuardrail", + request_serializer=agent_service.UpdateGuardrailRequest.serialize, + response_deserializer=gcc_guardrail.Guardrail.deserialize, + ) + return self._stubs["update_guardrail"] + + @property + def delete_guardrail( + self, + ) -> Callable[[agent_service.DeleteGuardrailRequest], empty_pb2.Empty]: + r"""Return a callable for the delete guardrail method over gRPC. + + Deletes the specified guardrail. + + Returns: + Callable[[~.DeleteGuardrailRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_guardrail" not in self._stubs: + self._stubs["delete_guardrail"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/DeleteGuardrail", + request_serializer=agent_service.DeleteGuardrailRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_guardrail"] + + @property + def list_deployments( + self, + ) -> Callable[ + [agent_service.ListDeploymentsRequest], agent_service.ListDeploymentsResponse + ]: + r"""Return a callable for the list deployments method over gRPC. + + Lists deployments in the given app. + + Returns: + Callable[[~.ListDeploymentsRequest], + ~.ListDeploymentsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_deployments" not in self._stubs: + self._stubs["list_deployments"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/ListDeployments", + request_serializer=agent_service.ListDeploymentsRequest.serialize, + response_deserializer=agent_service.ListDeploymentsResponse.deserialize, + ) + return self._stubs["list_deployments"] + + @property + def get_deployment( + self, + ) -> Callable[[agent_service.GetDeploymentRequest], deployment.Deployment]: + r"""Return a callable for the get deployment method over gRPC. + + Gets details of the specified deployment. + + Returns: + Callable[[~.GetDeploymentRequest], + ~.Deployment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_deployment" not in self._stubs: + self._stubs["get_deployment"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/GetDeployment", + request_serializer=agent_service.GetDeploymentRequest.serialize, + response_deserializer=deployment.Deployment.deserialize, + ) + return self._stubs["get_deployment"] + + @property + def create_deployment( + self, + ) -> Callable[[agent_service.CreateDeploymentRequest], gcc_deployment.Deployment]: + r"""Return a callable for the create deployment method over gRPC. + + Creates a new deployment in the given app. + + Returns: + Callable[[~.CreateDeploymentRequest], + ~.Deployment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_deployment" not in self._stubs: + self._stubs["create_deployment"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/CreateDeployment", + request_serializer=agent_service.CreateDeploymentRequest.serialize, + response_deserializer=gcc_deployment.Deployment.deserialize, + ) + return self._stubs["create_deployment"] + + @property + def update_deployment( + self, + ) -> Callable[[agent_service.UpdateDeploymentRequest], gcc_deployment.Deployment]: + r"""Return a callable for the update deployment method over gRPC. + + Updates the specified deployment. + + Returns: + Callable[[~.UpdateDeploymentRequest], + ~.Deployment]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_deployment" not in self._stubs: + self._stubs["update_deployment"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/UpdateDeployment", + request_serializer=agent_service.UpdateDeploymentRequest.serialize, + response_deserializer=gcc_deployment.Deployment.deserialize, + ) + return self._stubs["update_deployment"] + + @property + def delete_deployment( + self, + ) -> Callable[[agent_service.DeleteDeploymentRequest], empty_pb2.Empty]: + r"""Return a callable for the delete deployment method over gRPC. + + Deletes the specified deployment. + + Returns: + Callable[[~.DeleteDeploymentRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_deployment" not in self._stubs: + self._stubs["delete_deployment"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/DeleteDeployment", + request_serializer=agent_service.DeleteDeploymentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_deployment"] + + @property + def list_toolsets( + self, + ) -> Callable[ + [agent_service.ListToolsetsRequest], agent_service.ListToolsetsResponse + ]: + r"""Return a callable for the list toolsets method over gRPC. + + Lists toolsets in the given app. + + Returns: + Callable[[~.ListToolsetsRequest], + ~.ListToolsetsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_toolsets" not in self._stubs: + self._stubs["list_toolsets"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/ListToolsets", + request_serializer=agent_service.ListToolsetsRequest.serialize, + response_deserializer=agent_service.ListToolsetsResponse.deserialize, + ) + return self._stubs["list_toolsets"] + + @property + def get_toolset( + self, + ) -> Callable[[agent_service.GetToolsetRequest], toolset.Toolset]: + r"""Return a callable for the get toolset method over gRPC. + + Gets details of the specified toolset. + + Returns: + Callable[[~.GetToolsetRequest], + ~.Toolset]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_toolset" not in self._stubs: + self._stubs["get_toolset"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/GetToolset", + request_serializer=agent_service.GetToolsetRequest.serialize, + response_deserializer=toolset.Toolset.deserialize, + ) + return self._stubs["get_toolset"] + + @property + def create_toolset( + self, + ) -> Callable[[agent_service.CreateToolsetRequest], gcc_toolset.Toolset]: + r"""Return a callable for the create toolset method over gRPC. + + Creates a new toolset in the given app. + + Returns: + Callable[[~.CreateToolsetRequest], + ~.Toolset]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_toolset" not in self._stubs: + self._stubs["create_toolset"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/CreateToolset", + request_serializer=agent_service.CreateToolsetRequest.serialize, + response_deserializer=gcc_toolset.Toolset.deserialize, + ) + return self._stubs["create_toolset"] + + @property + def update_toolset( + self, + ) -> Callable[[agent_service.UpdateToolsetRequest], gcc_toolset.Toolset]: + r"""Return a callable for the update toolset method over gRPC. + + Updates the specified toolset. + + Returns: + Callable[[~.UpdateToolsetRequest], + ~.Toolset]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_toolset" not in self._stubs: + self._stubs["update_toolset"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/UpdateToolset", + request_serializer=agent_service.UpdateToolsetRequest.serialize, + response_deserializer=gcc_toolset.Toolset.deserialize, + ) + return self._stubs["update_toolset"] + + @property + def delete_toolset( + self, + ) -> Callable[[agent_service.DeleteToolsetRequest], empty_pb2.Empty]: + r"""Return a callable for the delete toolset method over gRPC. + + Deletes the specified toolset. + + Returns: + Callable[[~.DeleteToolsetRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_toolset" not in self._stubs: + self._stubs["delete_toolset"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/DeleteToolset", + request_serializer=agent_service.DeleteToolsetRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_toolset"] + + @property + def list_app_versions( + self, + ) -> Callable[ + [agent_service.ListAppVersionsRequest], agent_service.ListAppVersionsResponse + ]: + r"""Return a callable for the list app versions method over gRPC. + + Lists all app versions in the given app. + + Returns: + Callable[[~.ListAppVersionsRequest], + ~.ListAppVersionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_app_versions" not in self._stubs: + self._stubs["list_app_versions"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/ListAppVersions", + request_serializer=agent_service.ListAppVersionsRequest.serialize, + response_deserializer=agent_service.ListAppVersionsResponse.deserialize, + ) + return self._stubs["list_app_versions"] + + @property + def get_app_version( + self, + ) -> Callable[[agent_service.GetAppVersionRequest], app_version.AppVersion]: + r"""Return a callable for the get app version method over gRPC. + + Gets details of the specified app version. + + Returns: + Callable[[~.GetAppVersionRequest], + ~.AppVersion]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_app_version" not in self._stubs: + self._stubs["get_app_version"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/GetAppVersion", + request_serializer=agent_service.GetAppVersionRequest.serialize, + response_deserializer=app_version.AppVersion.deserialize, + ) + return self._stubs["get_app_version"] + + @property + def create_app_version( + self, + ) -> Callable[[agent_service.CreateAppVersionRequest], gcc_app_version.AppVersion]: + r"""Return a callable for the create app version method over gRPC. + + Creates a new app version in the given app. + + Returns: + Callable[[~.CreateAppVersionRequest], + ~.AppVersion]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_app_version" not in self._stubs: + self._stubs["create_app_version"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/CreateAppVersion", + request_serializer=agent_service.CreateAppVersionRequest.serialize, + response_deserializer=gcc_app_version.AppVersion.deserialize, + ) + return self._stubs["create_app_version"] + + @property + def delete_app_version( + self, + ) -> Callable[[agent_service.DeleteAppVersionRequest], empty_pb2.Empty]: + r"""Return a callable for the delete app version method over gRPC. + + Deletes the specified app version. + + Returns: + Callable[[~.DeleteAppVersionRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_app_version" not in self._stubs: + self._stubs["delete_app_version"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/DeleteAppVersion", + request_serializer=agent_service.DeleteAppVersionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_app_version"] + + @property + def restore_app_version( + self, + ) -> Callable[[agent_service.RestoreAppVersionRequest], operations_pb2.Operation]: + r"""Return a callable for the restore app version method over gRPC. + + Restores the specified app version. + This will create a new app version from the current + draft app and overwrite the current draft with the + specified app version. + + Returns: + Callable[[~.RestoreAppVersionRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "restore_app_version" not in self._stubs: + self._stubs["restore_app_version"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/RestoreAppVersion", + request_serializer=agent_service.RestoreAppVersionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["restore_app_version"] + + @property + def list_changelogs( + self, + ) -> Callable[ + [agent_service.ListChangelogsRequest], agent_service.ListChangelogsResponse + ]: + r"""Return a callable for the list changelogs method over gRPC. + + Lists the changelogs of the specified app. + + Returns: + Callable[[~.ListChangelogsRequest], + ~.ListChangelogsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_changelogs" not in self._stubs: + self._stubs["list_changelogs"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/ListChangelogs", + request_serializer=agent_service.ListChangelogsRequest.serialize, + response_deserializer=agent_service.ListChangelogsResponse.deserialize, + ) + return self._stubs["list_changelogs"] + + @property + def get_changelog( + self, + ) -> Callable[[agent_service.GetChangelogRequest], changelog.Changelog]: + r"""Return a callable for the get changelog method over gRPC. + + Gets the specified changelog. + + Returns: + Callable[[~.GetChangelogRequest], + ~.Changelog]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_changelog" not in self._stubs: + self._stubs["get_changelog"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/GetChangelog", + request_serializer=agent_service.GetChangelogRequest.serialize, + response_deserializer=changelog.Changelog.deserialize, + ) + return self._stubs["get_changelog"] + + def close(self): + self._logged_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("AgentServiceGrpcTransport",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/grpc_asyncio.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..c887211efa6f --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/grpc_asyncio.py @@ -0,0 +1,2076 @@ +# -*- coding: utf-8 -*- +# 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. +# +import inspect +import json +import logging as std_logging +import pickle +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +from grpc.experimental import aio # type: ignore + +from google.cloud.ces_v1beta.types import ( + agent, + agent_service, + app, + app_version, + changelog, + conversation, + deployment, + example, + guardrail, + tool, + toolset, +) +from google.cloud.ces_v1beta.types import agent as gcc_agent +from google.cloud.ces_v1beta.types import app as gcc_app +from google.cloud.ces_v1beta.types import app_version as gcc_app_version +from google.cloud.ces_v1beta.types import deployment as gcc_deployment +from google.cloud.ces_v1beta.types import example as gcc_example +from google.cloud.ces_v1beta.types import guardrail as gcc_guardrail +from google.cloud.ces_v1beta.types import tool as gcc_tool +from google.cloud.ces_v1beta.types import toolset as gcc_toolset + +from .base import DEFAULT_CLIENT_INFO, AgentServiceTransport +from .grpc import AgentServiceGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class AgentServiceGrpcAsyncIOTransport(AgentServiceTransport): + """gRPC AsyncIO backend transport for AgentService. + + The service that manages agent-related resources in Gemini + Enterprise for Customer Engagement (CES). + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "ces.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "ces.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'ces.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def list_apps( + self, + ) -> Callable[ + [agent_service.ListAppsRequest], Awaitable[agent_service.ListAppsResponse] + ]: + r"""Return a callable for the list apps method over gRPC. + + Lists apps in the given project and location. + + Returns: + Callable[[~.ListAppsRequest], + Awaitable[~.ListAppsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_apps" not in self._stubs: + self._stubs["list_apps"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/ListApps", + request_serializer=agent_service.ListAppsRequest.serialize, + response_deserializer=agent_service.ListAppsResponse.deserialize, + ) + return self._stubs["list_apps"] + + @property + def get_app(self) -> Callable[[agent_service.GetAppRequest], Awaitable[app.App]]: + r"""Return a callable for the get app method over gRPC. + + Gets details of the specified app. + + Returns: + Callable[[~.GetAppRequest], + Awaitable[~.App]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_app" not in self._stubs: + self._stubs["get_app"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/GetApp", + request_serializer=agent_service.GetAppRequest.serialize, + response_deserializer=app.App.deserialize, + ) + return self._stubs["get_app"] + + @property + def create_app( + self, + ) -> Callable[ + [agent_service.CreateAppRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the create app method over gRPC. + + Creates a new app in the given project and location. + + Returns: + Callable[[~.CreateAppRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_app" not in self._stubs: + self._stubs["create_app"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/CreateApp", + request_serializer=agent_service.CreateAppRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_app"] + + @property + def update_app( + self, + ) -> Callable[[agent_service.UpdateAppRequest], Awaitable[gcc_app.App]]: + r"""Return a callable for the update app method over gRPC. + + Updates the specified app. + + Returns: + Callable[[~.UpdateAppRequest], + Awaitable[~.App]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_app" not in self._stubs: + self._stubs["update_app"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/UpdateApp", + request_serializer=agent_service.UpdateAppRequest.serialize, + response_deserializer=gcc_app.App.deserialize, + ) + return self._stubs["update_app"] + + @property + def delete_app( + self, + ) -> Callable[ + [agent_service.DeleteAppRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the delete app method over gRPC. + + Deletes the specified app. + + Returns: + Callable[[~.DeleteAppRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_app" not in self._stubs: + self._stubs["delete_app"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/DeleteApp", + request_serializer=agent_service.DeleteAppRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_app"] + + @property + def export_app( + self, + ) -> Callable[ + [agent_service.ExportAppRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the export app method over gRPC. + + Exports the specified app. + + Returns: + Callable[[~.ExportAppRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "export_app" not in self._stubs: + self._stubs["export_app"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/ExportApp", + request_serializer=agent_service.ExportAppRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["export_app"] + + @property + def import_app( + self, + ) -> Callable[ + [agent_service.ImportAppRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the import app method over gRPC. + + Imports the specified app. + + Returns: + Callable[[~.ImportAppRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "import_app" not in self._stubs: + self._stubs["import_app"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/ImportApp", + request_serializer=agent_service.ImportAppRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["import_app"] + + @property + def list_agents( + self, + ) -> Callable[ + [agent_service.ListAgentsRequest], Awaitable[agent_service.ListAgentsResponse] + ]: + r"""Return a callable for the list agents method over gRPC. + + Lists agents in the given app. + + Returns: + Callable[[~.ListAgentsRequest], + Awaitable[~.ListAgentsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_agents" not in self._stubs: + self._stubs["list_agents"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/ListAgents", + request_serializer=agent_service.ListAgentsRequest.serialize, + response_deserializer=agent_service.ListAgentsResponse.deserialize, + ) + return self._stubs["list_agents"] + + @property + def get_agent( + self, + ) -> Callable[[agent_service.GetAgentRequest], Awaitable[agent.Agent]]: + r"""Return a callable for the get agent method over gRPC. + + Gets details of the specified agent. + + Returns: + Callable[[~.GetAgentRequest], + Awaitable[~.Agent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_agent" not in self._stubs: + self._stubs["get_agent"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/GetAgent", + request_serializer=agent_service.GetAgentRequest.serialize, + response_deserializer=agent.Agent.deserialize, + ) + return self._stubs["get_agent"] + + @property + def create_agent( + self, + ) -> Callable[[agent_service.CreateAgentRequest], Awaitable[gcc_agent.Agent]]: + r"""Return a callable for the create agent method over gRPC. + + Creates a new agent in the given app. + + Returns: + Callable[[~.CreateAgentRequest], + Awaitable[~.Agent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_agent" not in self._stubs: + self._stubs["create_agent"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/CreateAgent", + request_serializer=agent_service.CreateAgentRequest.serialize, + response_deserializer=gcc_agent.Agent.deserialize, + ) + return self._stubs["create_agent"] + + @property + def update_agent( + self, + ) -> Callable[[agent_service.UpdateAgentRequest], Awaitable[gcc_agent.Agent]]: + r"""Return a callable for the update agent method over gRPC. + + Updates the specified agent. + + Returns: + Callable[[~.UpdateAgentRequest], + Awaitable[~.Agent]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_agent" not in self._stubs: + self._stubs["update_agent"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/UpdateAgent", + request_serializer=agent_service.UpdateAgentRequest.serialize, + response_deserializer=gcc_agent.Agent.deserialize, + ) + return self._stubs["update_agent"] + + @property + def delete_agent( + self, + ) -> Callable[[agent_service.DeleteAgentRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete agent method over gRPC. + + Deletes the specified agent. + + Returns: + Callable[[~.DeleteAgentRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_agent" not in self._stubs: + self._stubs["delete_agent"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/DeleteAgent", + request_serializer=agent_service.DeleteAgentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_agent"] + + @property + def list_examples( + self, + ) -> Callable[ + [agent_service.ListExamplesRequest], + Awaitable[agent_service.ListExamplesResponse], + ]: + r"""Return a callable for the list examples method over gRPC. + + Lists examples in the given app. + + Returns: + Callable[[~.ListExamplesRequest], + Awaitable[~.ListExamplesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_examples" not in self._stubs: + self._stubs["list_examples"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/ListExamples", + request_serializer=agent_service.ListExamplesRequest.serialize, + response_deserializer=agent_service.ListExamplesResponse.deserialize, + ) + return self._stubs["list_examples"] + + @property + def get_example( + self, + ) -> Callable[[agent_service.GetExampleRequest], Awaitable[example.Example]]: + r"""Return a callable for the get example method over gRPC. + + Gets details of the specified example. + + Returns: + Callable[[~.GetExampleRequest], + Awaitable[~.Example]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_example" not in self._stubs: + self._stubs["get_example"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/GetExample", + request_serializer=agent_service.GetExampleRequest.serialize, + response_deserializer=example.Example.deserialize, + ) + return self._stubs["get_example"] + + @property + def create_example( + self, + ) -> Callable[[agent_service.CreateExampleRequest], Awaitable[gcc_example.Example]]: + r"""Return a callable for the create example method over gRPC. + + Creates a new example in the given app. + + Returns: + Callable[[~.CreateExampleRequest], + Awaitable[~.Example]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_example" not in self._stubs: + self._stubs["create_example"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/CreateExample", + request_serializer=agent_service.CreateExampleRequest.serialize, + response_deserializer=gcc_example.Example.deserialize, + ) + return self._stubs["create_example"] + + @property + def update_example( + self, + ) -> Callable[[agent_service.UpdateExampleRequest], Awaitable[gcc_example.Example]]: + r"""Return a callable for the update example method over gRPC. + + Updates the specified example. + + Returns: + Callable[[~.UpdateExampleRequest], + Awaitable[~.Example]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_example" not in self._stubs: + self._stubs["update_example"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/UpdateExample", + request_serializer=agent_service.UpdateExampleRequest.serialize, + response_deserializer=gcc_example.Example.deserialize, + ) + return self._stubs["update_example"] + + @property + def delete_example( + self, + ) -> Callable[[agent_service.DeleteExampleRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete example method over gRPC. + + Deletes the specified example. + + Returns: + Callable[[~.DeleteExampleRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_example" not in self._stubs: + self._stubs["delete_example"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/DeleteExample", + request_serializer=agent_service.DeleteExampleRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_example"] + + @property + def list_tools( + self, + ) -> Callable[ + [agent_service.ListToolsRequest], Awaitable[agent_service.ListToolsResponse] + ]: + r"""Return a callable for the list tools method over gRPC. + + Lists tools in the given app. + + Returns: + Callable[[~.ListToolsRequest], + Awaitable[~.ListToolsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_tools" not in self._stubs: + self._stubs["list_tools"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/ListTools", + request_serializer=agent_service.ListToolsRequest.serialize, + response_deserializer=agent_service.ListToolsResponse.deserialize, + ) + return self._stubs["list_tools"] + + @property + def get_tool( + self, + ) -> Callable[[agent_service.GetToolRequest], Awaitable[tool.Tool]]: + r"""Return a callable for the get tool method over gRPC. + + Gets details of the specified tool. + + Returns: + Callable[[~.GetToolRequest], + Awaitable[~.Tool]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_tool" not in self._stubs: + self._stubs["get_tool"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/GetTool", + request_serializer=agent_service.GetToolRequest.serialize, + response_deserializer=tool.Tool.deserialize, + ) + return self._stubs["get_tool"] + + @property + def list_conversations( + self, + ) -> Callable[ + [agent_service.ListConversationsRequest], + Awaitable[agent_service.ListConversationsResponse], + ]: + r"""Return a callable for the list conversations method over gRPC. + + Lists conversations in the given app. + + Returns: + Callable[[~.ListConversationsRequest], + Awaitable[~.ListConversationsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_conversations" not in self._stubs: + self._stubs["list_conversations"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/ListConversations", + request_serializer=agent_service.ListConversationsRequest.serialize, + response_deserializer=agent_service.ListConversationsResponse.deserialize, + ) + return self._stubs["list_conversations"] + + @property + def get_conversation( + self, + ) -> Callable[ + [agent_service.GetConversationRequest], Awaitable[conversation.Conversation] + ]: + r"""Return a callable for the get conversation method over gRPC. + + Gets details of the specified conversation. + + Returns: + Callable[[~.GetConversationRequest], + Awaitable[~.Conversation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_conversation" not in self._stubs: + self._stubs["get_conversation"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/GetConversation", + request_serializer=agent_service.GetConversationRequest.serialize, + response_deserializer=conversation.Conversation.deserialize, + ) + return self._stubs["get_conversation"] + + @property + def delete_conversation( + self, + ) -> Callable[ + [agent_service.DeleteConversationRequest], Awaitable[empty_pb2.Empty] + ]: + r"""Return a callable for the delete conversation method over gRPC. + + Deletes the specified conversation. + + Returns: + Callable[[~.DeleteConversationRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_conversation" not in self._stubs: + self._stubs["delete_conversation"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/DeleteConversation", + request_serializer=agent_service.DeleteConversationRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_conversation"] + + @property + def batch_delete_conversations( + self, + ) -> Callable[ + [agent_service.BatchDeleteConversationsRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the batch delete conversations method over gRPC. + + Batch deletes the specified conversations. + + Returns: + Callable[[~.BatchDeleteConversationsRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_delete_conversations" not in self._stubs: + self._stubs["batch_delete_conversations"] = ( + self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/BatchDeleteConversations", + request_serializer=agent_service.BatchDeleteConversationsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["batch_delete_conversations"] + + @property + def create_tool( + self, + ) -> Callable[[agent_service.CreateToolRequest], Awaitable[gcc_tool.Tool]]: + r"""Return a callable for the create tool method over gRPC. + + Creates a new tool in the given app. + + Returns: + Callable[[~.CreateToolRequest], + Awaitable[~.Tool]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_tool" not in self._stubs: + self._stubs["create_tool"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/CreateTool", + request_serializer=agent_service.CreateToolRequest.serialize, + response_deserializer=gcc_tool.Tool.deserialize, + ) + return self._stubs["create_tool"] + + @property + def update_tool( + self, + ) -> Callable[[agent_service.UpdateToolRequest], Awaitable[gcc_tool.Tool]]: + r"""Return a callable for the update tool method over gRPC. + + Updates the specified tool. + + Returns: + Callable[[~.UpdateToolRequest], + Awaitable[~.Tool]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_tool" not in self._stubs: + self._stubs["update_tool"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/UpdateTool", + request_serializer=agent_service.UpdateToolRequest.serialize, + response_deserializer=gcc_tool.Tool.deserialize, + ) + return self._stubs["update_tool"] + + @property + def delete_tool( + self, + ) -> Callable[[agent_service.DeleteToolRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete tool method over gRPC. + + Deletes the specified tool. + + Returns: + Callable[[~.DeleteToolRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_tool" not in self._stubs: + self._stubs["delete_tool"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/DeleteTool", + request_serializer=agent_service.DeleteToolRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_tool"] + + @property + def list_guardrails( + self, + ) -> Callable[ + [agent_service.ListGuardrailsRequest], + Awaitable[agent_service.ListGuardrailsResponse], + ]: + r"""Return a callable for the list guardrails method over gRPC. + + Lists guardrails in the given app. + + Returns: + Callable[[~.ListGuardrailsRequest], + Awaitable[~.ListGuardrailsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_guardrails" not in self._stubs: + self._stubs["list_guardrails"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/ListGuardrails", + request_serializer=agent_service.ListGuardrailsRequest.serialize, + response_deserializer=agent_service.ListGuardrailsResponse.deserialize, + ) + return self._stubs["list_guardrails"] + + @property + def get_guardrail( + self, + ) -> Callable[[agent_service.GetGuardrailRequest], Awaitable[guardrail.Guardrail]]: + r"""Return a callable for the get guardrail method over gRPC. + + Gets details of the specified guardrail. + + Returns: + Callable[[~.GetGuardrailRequest], + Awaitable[~.Guardrail]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_guardrail" not in self._stubs: + self._stubs["get_guardrail"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/GetGuardrail", + request_serializer=agent_service.GetGuardrailRequest.serialize, + response_deserializer=guardrail.Guardrail.deserialize, + ) + return self._stubs["get_guardrail"] + + @property + def create_guardrail( + self, + ) -> Callable[ + [agent_service.CreateGuardrailRequest], Awaitable[gcc_guardrail.Guardrail] + ]: + r"""Return a callable for the create guardrail method over gRPC. + + Creates a new guardrail in the given app. + + Returns: + Callable[[~.CreateGuardrailRequest], + Awaitable[~.Guardrail]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_guardrail" not in self._stubs: + self._stubs["create_guardrail"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/CreateGuardrail", + request_serializer=agent_service.CreateGuardrailRequest.serialize, + response_deserializer=gcc_guardrail.Guardrail.deserialize, + ) + return self._stubs["create_guardrail"] + + @property + def update_guardrail( + self, + ) -> Callable[ + [agent_service.UpdateGuardrailRequest], Awaitable[gcc_guardrail.Guardrail] + ]: + r"""Return a callable for the update guardrail method over gRPC. + + Updates the specified guardrail. + + Returns: + Callable[[~.UpdateGuardrailRequest], + Awaitable[~.Guardrail]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_guardrail" not in self._stubs: + self._stubs["update_guardrail"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/UpdateGuardrail", + request_serializer=agent_service.UpdateGuardrailRequest.serialize, + response_deserializer=gcc_guardrail.Guardrail.deserialize, + ) + return self._stubs["update_guardrail"] + + @property + def delete_guardrail( + self, + ) -> Callable[[agent_service.DeleteGuardrailRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete guardrail method over gRPC. + + Deletes the specified guardrail. + + Returns: + Callable[[~.DeleteGuardrailRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_guardrail" not in self._stubs: + self._stubs["delete_guardrail"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/DeleteGuardrail", + request_serializer=agent_service.DeleteGuardrailRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_guardrail"] + + @property + def list_deployments( + self, + ) -> Callable[ + [agent_service.ListDeploymentsRequest], + Awaitable[agent_service.ListDeploymentsResponse], + ]: + r"""Return a callable for the list deployments method over gRPC. + + Lists deployments in the given app. + + Returns: + Callable[[~.ListDeploymentsRequest], + Awaitable[~.ListDeploymentsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_deployments" not in self._stubs: + self._stubs["list_deployments"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/ListDeployments", + request_serializer=agent_service.ListDeploymentsRequest.serialize, + response_deserializer=agent_service.ListDeploymentsResponse.deserialize, + ) + return self._stubs["list_deployments"] + + @property + def get_deployment( + self, + ) -> Callable[ + [agent_service.GetDeploymentRequest], Awaitable[deployment.Deployment] + ]: + r"""Return a callable for the get deployment method over gRPC. + + Gets details of the specified deployment. + + Returns: + Callable[[~.GetDeploymentRequest], + Awaitable[~.Deployment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_deployment" not in self._stubs: + self._stubs["get_deployment"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/GetDeployment", + request_serializer=agent_service.GetDeploymentRequest.serialize, + response_deserializer=deployment.Deployment.deserialize, + ) + return self._stubs["get_deployment"] + + @property + def create_deployment( + self, + ) -> Callable[ + [agent_service.CreateDeploymentRequest], Awaitable[gcc_deployment.Deployment] + ]: + r"""Return a callable for the create deployment method over gRPC. + + Creates a new deployment in the given app. + + Returns: + Callable[[~.CreateDeploymentRequest], + Awaitable[~.Deployment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_deployment" not in self._stubs: + self._stubs["create_deployment"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/CreateDeployment", + request_serializer=agent_service.CreateDeploymentRequest.serialize, + response_deserializer=gcc_deployment.Deployment.deserialize, + ) + return self._stubs["create_deployment"] + + @property + def update_deployment( + self, + ) -> Callable[ + [agent_service.UpdateDeploymentRequest], Awaitable[gcc_deployment.Deployment] + ]: + r"""Return a callable for the update deployment method over gRPC. + + Updates the specified deployment. + + Returns: + Callable[[~.UpdateDeploymentRequest], + Awaitable[~.Deployment]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_deployment" not in self._stubs: + self._stubs["update_deployment"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/UpdateDeployment", + request_serializer=agent_service.UpdateDeploymentRequest.serialize, + response_deserializer=gcc_deployment.Deployment.deserialize, + ) + return self._stubs["update_deployment"] + + @property + def delete_deployment( + self, + ) -> Callable[[agent_service.DeleteDeploymentRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete deployment method over gRPC. + + Deletes the specified deployment. + + Returns: + Callable[[~.DeleteDeploymentRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_deployment" not in self._stubs: + self._stubs["delete_deployment"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/DeleteDeployment", + request_serializer=agent_service.DeleteDeploymentRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_deployment"] + + @property + def list_toolsets( + self, + ) -> Callable[ + [agent_service.ListToolsetsRequest], + Awaitable[agent_service.ListToolsetsResponse], + ]: + r"""Return a callable for the list toolsets method over gRPC. + + Lists toolsets in the given app. + + Returns: + Callable[[~.ListToolsetsRequest], + Awaitable[~.ListToolsetsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_toolsets" not in self._stubs: + self._stubs["list_toolsets"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/ListToolsets", + request_serializer=agent_service.ListToolsetsRequest.serialize, + response_deserializer=agent_service.ListToolsetsResponse.deserialize, + ) + return self._stubs["list_toolsets"] + + @property + def get_toolset( + self, + ) -> Callable[[agent_service.GetToolsetRequest], Awaitable[toolset.Toolset]]: + r"""Return a callable for the get toolset method over gRPC. + + Gets details of the specified toolset. + + Returns: + Callable[[~.GetToolsetRequest], + Awaitable[~.Toolset]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_toolset" not in self._stubs: + self._stubs["get_toolset"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/GetToolset", + request_serializer=agent_service.GetToolsetRequest.serialize, + response_deserializer=toolset.Toolset.deserialize, + ) + return self._stubs["get_toolset"] + + @property + def create_toolset( + self, + ) -> Callable[[agent_service.CreateToolsetRequest], Awaitable[gcc_toolset.Toolset]]: + r"""Return a callable for the create toolset method over gRPC. + + Creates a new toolset in the given app. + + Returns: + Callable[[~.CreateToolsetRequest], + Awaitable[~.Toolset]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_toolset" not in self._stubs: + self._stubs["create_toolset"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/CreateToolset", + request_serializer=agent_service.CreateToolsetRequest.serialize, + response_deserializer=gcc_toolset.Toolset.deserialize, + ) + return self._stubs["create_toolset"] + + @property + def update_toolset( + self, + ) -> Callable[[agent_service.UpdateToolsetRequest], Awaitable[gcc_toolset.Toolset]]: + r"""Return a callable for the update toolset method over gRPC. + + Updates the specified toolset. + + Returns: + Callable[[~.UpdateToolsetRequest], + Awaitable[~.Toolset]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_toolset" not in self._stubs: + self._stubs["update_toolset"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/UpdateToolset", + request_serializer=agent_service.UpdateToolsetRequest.serialize, + response_deserializer=gcc_toolset.Toolset.deserialize, + ) + return self._stubs["update_toolset"] + + @property + def delete_toolset( + self, + ) -> Callable[[agent_service.DeleteToolsetRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete toolset method over gRPC. + + Deletes the specified toolset. + + Returns: + Callable[[~.DeleteToolsetRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_toolset" not in self._stubs: + self._stubs["delete_toolset"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/DeleteToolset", + request_serializer=agent_service.DeleteToolsetRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_toolset"] + + @property + def list_app_versions( + self, + ) -> Callable[ + [agent_service.ListAppVersionsRequest], + Awaitable[agent_service.ListAppVersionsResponse], + ]: + r"""Return a callable for the list app versions method over gRPC. + + Lists all app versions in the given app. + + Returns: + Callable[[~.ListAppVersionsRequest], + Awaitable[~.ListAppVersionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_app_versions" not in self._stubs: + self._stubs["list_app_versions"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/ListAppVersions", + request_serializer=agent_service.ListAppVersionsRequest.serialize, + response_deserializer=agent_service.ListAppVersionsResponse.deserialize, + ) + return self._stubs["list_app_versions"] + + @property + def get_app_version( + self, + ) -> Callable[ + [agent_service.GetAppVersionRequest], Awaitable[app_version.AppVersion] + ]: + r"""Return a callable for the get app version method over gRPC. + + Gets details of the specified app version. + + Returns: + Callable[[~.GetAppVersionRequest], + Awaitable[~.AppVersion]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_app_version" not in self._stubs: + self._stubs["get_app_version"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/GetAppVersion", + request_serializer=agent_service.GetAppVersionRequest.serialize, + response_deserializer=app_version.AppVersion.deserialize, + ) + return self._stubs["get_app_version"] + + @property + def create_app_version( + self, + ) -> Callable[ + [agent_service.CreateAppVersionRequest], Awaitable[gcc_app_version.AppVersion] + ]: + r"""Return a callable for the create app version method over gRPC. + + Creates a new app version in the given app. + + Returns: + Callable[[~.CreateAppVersionRequest], + Awaitable[~.AppVersion]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_app_version" not in self._stubs: + self._stubs["create_app_version"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/CreateAppVersion", + request_serializer=agent_service.CreateAppVersionRequest.serialize, + response_deserializer=gcc_app_version.AppVersion.deserialize, + ) + return self._stubs["create_app_version"] + + @property + def delete_app_version( + self, + ) -> Callable[[agent_service.DeleteAppVersionRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete app version method over gRPC. + + Deletes the specified app version. + + Returns: + Callable[[~.DeleteAppVersionRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_app_version" not in self._stubs: + self._stubs["delete_app_version"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/DeleteAppVersion", + request_serializer=agent_service.DeleteAppVersionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_app_version"] + + @property + def restore_app_version( + self, + ) -> Callable[ + [agent_service.RestoreAppVersionRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the restore app version method over gRPC. + + Restores the specified app version. + This will create a new app version from the current + draft app and overwrite the current draft with the + specified app version. + + Returns: + Callable[[~.RestoreAppVersionRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "restore_app_version" not in self._stubs: + self._stubs["restore_app_version"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/RestoreAppVersion", + request_serializer=agent_service.RestoreAppVersionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["restore_app_version"] + + @property + def list_changelogs( + self, + ) -> Callable[ + [agent_service.ListChangelogsRequest], + Awaitable[agent_service.ListChangelogsResponse], + ]: + r"""Return a callable for the list changelogs method over gRPC. + + Lists the changelogs of the specified app. + + Returns: + Callable[[~.ListChangelogsRequest], + Awaitable[~.ListChangelogsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_changelogs" not in self._stubs: + self._stubs["list_changelogs"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/ListChangelogs", + request_serializer=agent_service.ListChangelogsRequest.serialize, + response_deserializer=agent_service.ListChangelogsResponse.deserialize, + ) + return self._stubs["list_changelogs"] + + @property + def get_changelog( + self, + ) -> Callable[[agent_service.GetChangelogRequest], Awaitable[changelog.Changelog]]: + r"""Return a callable for the get changelog method over gRPC. + + Gets the specified changelog. + + Returns: + Callable[[~.GetChangelogRequest], + Awaitable[~.Changelog]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_changelog" not in self._stubs: + self._stubs["get_changelog"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.AgentService/GetChangelog", + request_serializer=agent_service.GetChangelogRequest.serialize, + response_deserializer=changelog.Changelog.deserialize, + ) + return self._stubs["get_changelog"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.list_apps: self._wrap_method( + self.list_apps, + default_timeout=None, + client_info=client_info, + ), + self.get_app: self._wrap_method( + self.get_app, + default_timeout=None, + client_info=client_info, + ), + self.create_app: self._wrap_method( + self.create_app, + default_timeout=None, + client_info=client_info, + ), + self.update_app: self._wrap_method( + self.update_app, + default_timeout=None, + client_info=client_info, + ), + self.delete_app: self._wrap_method( + self.delete_app, + default_timeout=None, + client_info=client_info, + ), + self.export_app: self._wrap_method( + self.export_app, + default_timeout=None, + client_info=client_info, + ), + self.import_app: self._wrap_method( + self.import_app, + default_timeout=None, + client_info=client_info, + ), + self.list_agents: self._wrap_method( + self.list_agents, + default_timeout=None, + client_info=client_info, + ), + self.get_agent: self._wrap_method( + self.get_agent, + default_timeout=None, + client_info=client_info, + ), + self.create_agent: self._wrap_method( + self.create_agent, + default_timeout=None, + client_info=client_info, + ), + self.update_agent: self._wrap_method( + self.update_agent, + default_timeout=None, + client_info=client_info, + ), + self.delete_agent: self._wrap_method( + self.delete_agent, + default_timeout=None, + client_info=client_info, + ), + self.list_examples: self._wrap_method( + self.list_examples, + default_timeout=None, + client_info=client_info, + ), + self.get_example: self._wrap_method( + self.get_example, + default_timeout=None, + client_info=client_info, + ), + self.create_example: self._wrap_method( + self.create_example, + default_timeout=None, + client_info=client_info, + ), + self.update_example: self._wrap_method( + self.update_example, + default_timeout=None, + client_info=client_info, + ), + self.delete_example: self._wrap_method( + self.delete_example, + default_timeout=None, + client_info=client_info, + ), + self.list_tools: self._wrap_method( + self.list_tools, + default_timeout=None, + client_info=client_info, + ), + self.get_tool: self._wrap_method( + self.get_tool, + default_timeout=None, + client_info=client_info, + ), + self.list_conversations: self._wrap_method( + self.list_conversations, + default_timeout=None, + client_info=client_info, + ), + self.get_conversation: self._wrap_method( + self.get_conversation, + default_timeout=None, + client_info=client_info, + ), + self.delete_conversation: self._wrap_method( + self.delete_conversation, + default_timeout=None, + client_info=client_info, + ), + self.batch_delete_conversations: self._wrap_method( + self.batch_delete_conversations, + default_timeout=None, + client_info=client_info, + ), + self.create_tool: self._wrap_method( + self.create_tool, + default_timeout=None, + client_info=client_info, + ), + self.update_tool: self._wrap_method( + self.update_tool, + default_timeout=None, + client_info=client_info, + ), + self.delete_tool: self._wrap_method( + self.delete_tool, + default_timeout=None, + client_info=client_info, + ), + self.list_guardrails: self._wrap_method( + self.list_guardrails, + default_timeout=None, + client_info=client_info, + ), + self.get_guardrail: self._wrap_method( + self.get_guardrail, + default_timeout=None, + client_info=client_info, + ), + self.create_guardrail: self._wrap_method( + self.create_guardrail, + default_timeout=None, + client_info=client_info, + ), + self.update_guardrail: self._wrap_method( + self.update_guardrail, + default_timeout=None, + client_info=client_info, + ), + self.delete_guardrail: self._wrap_method( + self.delete_guardrail, + default_timeout=None, + client_info=client_info, + ), + self.list_deployments: self._wrap_method( + self.list_deployments, + default_timeout=None, + client_info=client_info, + ), + self.get_deployment: self._wrap_method( + self.get_deployment, + default_timeout=None, + client_info=client_info, + ), + self.create_deployment: self._wrap_method( + self.create_deployment, + default_timeout=None, + client_info=client_info, + ), + self.update_deployment: self._wrap_method( + self.update_deployment, + default_timeout=None, + client_info=client_info, + ), + self.delete_deployment: self._wrap_method( + self.delete_deployment, + default_timeout=None, + client_info=client_info, + ), + self.list_toolsets: self._wrap_method( + self.list_toolsets, + default_timeout=None, + client_info=client_info, + ), + self.get_toolset: self._wrap_method( + self.get_toolset, + default_timeout=None, + client_info=client_info, + ), + self.create_toolset: self._wrap_method( + self.create_toolset, + default_timeout=None, + client_info=client_info, + ), + self.update_toolset: self._wrap_method( + self.update_toolset, + default_timeout=None, + client_info=client_info, + ), + self.delete_toolset: self._wrap_method( + self.delete_toolset, + default_timeout=None, + client_info=client_info, + ), + self.list_app_versions: self._wrap_method( + self.list_app_versions, + default_timeout=None, + client_info=client_info, + ), + self.get_app_version: self._wrap_method( + self.get_app_version, + default_timeout=None, + client_info=client_info, + ), + self.create_app_version: self._wrap_method( + self.create_app_version, + default_timeout=None, + client_info=client_info, + ), + self.delete_app_version: self._wrap_method( + self.delete_app_version, + default_timeout=None, + client_info=client_info, + ), + self.restore_app_version: self._wrap_method( + self.restore_app_version, + default_timeout=None, + client_info=client_info, + ), + self.list_changelogs: self._wrap_method( + self.list_changelogs, + default_timeout=None, + client_info=client_info, + ), + self.get_changelog: self._wrap_method( + self.get_changelog, + default_timeout=None, + client_info=client_info, + ), + self.get_location: self._wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: self._wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + +__all__ = ("AgentServiceGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/rest.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/rest.py new file mode 100644 index 000000000000..722f0be6d81b --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/rest.py @@ -0,0 +1,10943 @@ +# -*- coding: utf-8 -*- +# 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. +# +import dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.ces_v1beta.types import ( + agent, + agent_service, + app, + app_version, + changelog, + conversation, + deployment, + example, + guardrail, + tool, + toolset, +) +from google.cloud.ces_v1beta.types import agent as gcc_agent +from google.cloud.ces_v1beta.types import app as gcc_app +from google.cloud.ces_v1beta.types import app_version as gcc_app_version +from google.cloud.ces_v1beta.types import deployment as gcc_deployment +from google.cloud.ces_v1beta.types import example as gcc_example +from google.cloud.ces_v1beta.types import guardrail as gcc_guardrail +from google.cloud.ces_v1beta.types import tool as gcc_tool +from google.cloud.ces_v1beta.types import toolset as gcc_toolset + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseAgentServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class AgentServiceRestInterceptor: + """Interceptor for AgentService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the AgentServiceRestTransport. + + .. code-block:: python + class MyCustomAgentServiceInterceptor(AgentServiceRestInterceptor): + def pre_batch_delete_conversations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_delete_conversations(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_agent(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_agent(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_app(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_app(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_app_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_app_version(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_deployment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_deployment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_example(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_example(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_guardrail(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_guardrail(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_tool(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_tool(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_toolset(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_toolset(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_agent(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_app(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_app(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_app_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_conversation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_deployment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_example(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_guardrail(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_tool(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_toolset(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_export_app(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_export_app(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_agent(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_agent(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_app(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_app(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_app_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_app_version(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_changelog(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_changelog(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_conversation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_conversation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_deployment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_deployment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_example(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_example(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_guardrail(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_guardrail(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_tool(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_tool(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_toolset(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_toolset(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_import_app(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_import_app(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_agents(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_agents(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_apps(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_apps(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_app_versions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_app_versions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_changelogs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_changelogs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_conversations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_conversations(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_deployments(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_deployments(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_examples(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_examples(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_guardrails(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_guardrails(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_tools(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_tools(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_toolsets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_toolsets(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_restore_app_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_restore_app_version(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_agent(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_agent(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_app(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_app(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_deployment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_deployment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_example(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_example(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_guardrail(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_guardrail(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_tool(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_tool(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_toolset(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_toolset(self, response): + logging.log(f"Received response: {response}") + return response + + transport = AgentServiceRestTransport(interceptor=MyCustomAgentServiceInterceptor()) + client = AgentServiceClient(transport=transport) + + + """ + + def pre_batch_delete_conversations( + self, + request: agent_service.BatchDeleteConversationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.BatchDeleteConversationsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for batch_delete_conversations + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_batch_delete_conversations( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for batch_delete_conversations + + DEPRECATED. Please use the `post_batch_delete_conversations_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_batch_delete_conversations` interceptor runs + before the `post_batch_delete_conversations_with_metadata` interceptor. + """ + return response + + def post_batch_delete_conversations_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for batch_delete_conversations + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_batch_delete_conversations_with_metadata` + interceptor in new development instead of the `post_batch_delete_conversations` interceptor. + When both interceptors are used, this `post_batch_delete_conversations_with_metadata` interceptor runs after the + `post_batch_delete_conversations` interceptor. The (possibly modified) response returned by + `post_batch_delete_conversations` will be passed to + `post_batch_delete_conversations_with_metadata`. + """ + return response, metadata + + def pre_create_agent( + self, + request: agent_service.CreateAgentRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.CreateAgentRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_agent + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_create_agent(self, response: gcc_agent.Agent) -> gcc_agent.Agent: + """Post-rpc interceptor for create_agent + + DEPRECATED. Please use the `post_create_agent_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_create_agent` interceptor runs + before the `post_create_agent_with_metadata` interceptor. + """ + return response + + def post_create_agent_with_metadata( + self, + response: gcc_agent.Agent, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gcc_agent.Agent, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_agent + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_create_agent_with_metadata` + interceptor in new development instead of the `post_create_agent` interceptor. + When both interceptors are used, this `post_create_agent_with_metadata` interceptor runs after the + `post_create_agent` interceptor. The (possibly modified) response returned by + `post_create_agent` will be passed to + `post_create_agent_with_metadata`. + """ + return response, metadata + + def pre_create_app( + self, + request: agent_service.CreateAppRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[agent_service.CreateAppRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_app + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_create_app( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_app + + DEPRECATED. Please use the `post_create_app_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_create_app` interceptor runs + before the `post_create_app_with_metadata` interceptor. + """ + return response + + def post_create_app_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_app + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_create_app_with_metadata` + interceptor in new development instead of the `post_create_app` interceptor. + When both interceptors are used, this `post_create_app_with_metadata` interceptor runs after the + `post_create_app` interceptor. The (possibly modified) response returned by + `post_create_app` will be passed to + `post_create_app_with_metadata`. + """ + return response, metadata + + def pre_create_app_version( + self, + request: agent_service.CreateAppVersionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.CreateAppVersionRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_app_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_create_app_version( + self, response: gcc_app_version.AppVersion + ) -> gcc_app_version.AppVersion: + """Post-rpc interceptor for create_app_version + + DEPRECATED. Please use the `post_create_app_version_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_create_app_version` interceptor runs + before the `post_create_app_version_with_metadata` interceptor. + """ + return response + + def post_create_app_version_with_metadata( + self, + response: gcc_app_version.AppVersion, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gcc_app_version.AppVersion, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_app_version + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_create_app_version_with_metadata` + interceptor in new development instead of the `post_create_app_version` interceptor. + When both interceptors are used, this `post_create_app_version_with_metadata` interceptor runs after the + `post_create_app_version` interceptor. The (possibly modified) response returned by + `post_create_app_version` will be passed to + `post_create_app_version_with_metadata`. + """ + return response, metadata + + def pre_create_deployment( + self, + request: agent_service.CreateDeploymentRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.CreateDeploymentRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_deployment + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_create_deployment( + self, response: gcc_deployment.Deployment + ) -> gcc_deployment.Deployment: + """Post-rpc interceptor for create_deployment + + DEPRECATED. Please use the `post_create_deployment_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_create_deployment` interceptor runs + before the `post_create_deployment_with_metadata` interceptor. + """ + return response + + def post_create_deployment_with_metadata( + self, + response: gcc_deployment.Deployment, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gcc_deployment.Deployment, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_deployment + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_create_deployment_with_metadata` + interceptor in new development instead of the `post_create_deployment` interceptor. + When both interceptors are used, this `post_create_deployment_with_metadata` interceptor runs after the + `post_create_deployment` interceptor. The (possibly modified) response returned by + `post_create_deployment` will be passed to + `post_create_deployment_with_metadata`. + """ + return response, metadata + + def pre_create_example( + self, + request: agent_service.CreateExampleRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.CreateExampleRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_example + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_create_example(self, response: gcc_example.Example) -> gcc_example.Example: + """Post-rpc interceptor for create_example + + DEPRECATED. Please use the `post_create_example_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_create_example` interceptor runs + before the `post_create_example_with_metadata` interceptor. + """ + return response + + def post_create_example_with_metadata( + self, + response: gcc_example.Example, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gcc_example.Example, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_example + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_create_example_with_metadata` + interceptor in new development instead of the `post_create_example` interceptor. + When both interceptors are used, this `post_create_example_with_metadata` interceptor runs after the + `post_create_example` interceptor. The (possibly modified) response returned by + `post_create_example` will be passed to + `post_create_example_with_metadata`. + """ + return response, metadata + + def pre_create_guardrail( + self, + request: agent_service.CreateGuardrailRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.CreateGuardrailRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_guardrail + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_create_guardrail( + self, response: gcc_guardrail.Guardrail + ) -> gcc_guardrail.Guardrail: + """Post-rpc interceptor for create_guardrail + + DEPRECATED. Please use the `post_create_guardrail_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_create_guardrail` interceptor runs + before the `post_create_guardrail_with_metadata` interceptor. + """ + return response + + def post_create_guardrail_with_metadata( + self, + response: gcc_guardrail.Guardrail, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gcc_guardrail.Guardrail, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_guardrail + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_create_guardrail_with_metadata` + interceptor in new development instead of the `post_create_guardrail` interceptor. + When both interceptors are used, this `post_create_guardrail_with_metadata` interceptor runs after the + `post_create_guardrail` interceptor. The (possibly modified) response returned by + `post_create_guardrail` will be passed to + `post_create_guardrail_with_metadata`. + """ + return response, metadata + + def pre_create_tool( + self, + request: agent_service.CreateToolRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.CreateToolRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_tool + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_create_tool(self, response: gcc_tool.Tool) -> gcc_tool.Tool: + """Post-rpc interceptor for create_tool + + DEPRECATED. Please use the `post_create_tool_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_create_tool` interceptor runs + before the `post_create_tool_with_metadata` interceptor. + """ + return response + + def post_create_tool_with_metadata( + self, response: gcc_tool.Tool, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[gcc_tool.Tool, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_tool + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_create_tool_with_metadata` + interceptor in new development instead of the `post_create_tool` interceptor. + When both interceptors are used, this `post_create_tool_with_metadata` interceptor runs after the + `post_create_tool` interceptor. The (possibly modified) response returned by + `post_create_tool` will be passed to + `post_create_tool_with_metadata`. + """ + return response, metadata + + def pre_create_toolset( + self, + request: agent_service.CreateToolsetRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.CreateToolsetRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_toolset + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_create_toolset(self, response: gcc_toolset.Toolset) -> gcc_toolset.Toolset: + """Post-rpc interceptor for create_toolset + + DEPRECATED. Please use the `post_create_toolset_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_create_toolset` interceptor runs + before the `post_create_toolset_with_metadata` interceptor. + """ + return response + + def post_create_toolset_with_metadata( + self, + response: gcc_toolset.Toolset, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gcc_toolset.Toolset, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_toolset + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_create_toolset_with_metadata` + interceptor in new development instead of the `post_create_toolset` interceptor. + When both interceptors are used, this `post_create_toolset_with_metadata` interceptor runs after the + `post_create_toolset` interceptor. The (possibly modified) response returned by + `post_create_toolset` will be passed to + `post_create_toolset_with_metadata`. + """ + return response, metadata + + def pre_delete_agent( + self, + request: agent_service.DeleteAgentRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.DeleteAgentRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_agent + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def pre_delete_app( + self, + request: agent_service.DeleteAppRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[agent_service.DeleteAppRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_app + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_delete_app( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_app + + DEPRECATED. Please use the `post_delete_app_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_delete_app` interceptor runs + before the `post_delete_app_with_metadata` interceptor. + """ + return response + + def post_delete_app_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_app + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_delete_app_with_metadata` + interceptor in new development instead of the `post_delete_app` interceptor. + When both interceptors are used, this `post_delete_app_with_metadata` interceptor runs after the + `post_delete_app` interceptor. The (possibly modified) response returned by + `post_delete_app` will be passed to + `post_delete_app_with_metadata`. + """ + return response, metadata + + def pre_delete_app_version( + self, + request: agent_service.DeleteAppVersionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.DeleteAppVersionRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_app_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def pre_delete_conversation( + self, + request: agent_service.DeleteConversationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.DeleteConversationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_conversation + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def pre_delete_deployment( + self, + request: agent_service.DeleteDeploymentRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.DeleteDeploymentRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_deployment + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def pre_delete_example( + self, + request: agent_service.DeleteExampleRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.DeleteExampleRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_example + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def pre_delete_guardrail( + self, + request: agent_service.DeleteGuardrailRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.DeleteGuardrailRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_guardrail + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def pre_delete_tool( + self, + request: agent_service.DeleteToolRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.DeleteToolRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_tool + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def pre_delete_toolset( + self, + request: agent_service.DeleteToolsetRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.DeleteToolsetRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_toolset + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def pre_export_app( + self, + request: agent_service.ExportAppRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[agent_service.ExportAppRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for export_app + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_export_app( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for export_app + + DEPRECATED. Please use the `post_export_app_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_export_app` interceptor runs + before the `post_export_app_with_metadata` interceptor. + """ + return response + + def post_export_app_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for export_app + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_export_app_with_metadata` + interceptor in new development instead of the `post_export_app` interceptor. + When both interceptors are used, this `post_export_app_with_metadata` interceptor runs after the + `post_export_app` interceptor. The (possibly modified) response returned by + `post_export_app` will be passed to + `post_export_app_with_metadata`. + """ + return response, metadata + + def pre_get_agent( + self, + request: agent_service.GetAgentRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[agent_service.GetAgentRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_agent + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_get_agent(self, response: agent.Agent) -> agent.Agent: + """Post-rpc interceptor for get_agent + + DEPRECATED. Please use the `post_get_agent_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_get_agent` interceptor runs + before the `post_get_agent_with_metadata` interceptor. + """ + return response + + def post_get_agent_with_metadata( + self, response: agent.Agent, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[agent.Agent, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_agent + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_get_agent_with_metadata` + interceptor in new development instead of the `post_get_agent` interceptor. + When both interceptors are used, this `post_get_agent_with_metadata` interceptor runs after the + `post_get_agent` interceptor. The (possibly modified) response returned by + `post_get_agent` will be passed to + `post_get_agent_with_metadata`. + """ + return response, metadata + + def pre_get_app( + self, + request: agent_service.GetAppRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[agent_service.GetAppRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_app + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_get_app(self, response: app.App) -> app.App: + """Post-rpc interceptor for get_app + + DEPRECATED. Please use the `post_get_app_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_get_app` interceptor runs + before the `post_get_app_with_metadata` interceptor. + """ + return response + + def post_get_app_with_metadata( + self, response: app.App, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[app.App, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_app + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_get_app_with_metadata` + interceptor in new development instead of the `post_get_app` interceptor. + When both interceptors are used, this `post_get_app_with_metadata` interceptor runs after the + `post_get_app` interceptor. The (possibly modified) response returned by + `post_get_app` will be passed to + `post_get_app_with_metadata`. + """ + return response, metadata + + def pre_get_app_version( + self, + request: agent_service.GetAppVersionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.GetAppVersionRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_app_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_get_app_version( + self, response: app_version.AppVersion + ) -> app_version.AppVersion: + """Post-rpc interceptor for get_app_version + + DEPRECATED. Please use the `post_get_app_version_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_get_app_version` interceptor runs + before the `post_get_app_version_with_metadata` interceptor. + """ + return response + + def post_get_app_version_with_metadata( + self, + response: app_version.AppVersion, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[app_version.AppVersion, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_app_version + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_get_app_version_with_metadata` + interceptor in new development instead of the `post_get_app_version` interceptor. + When both interceptors are used, this `post_get_app_version_with_metadata` interceptor runs after the + `post_get_app_version` interceptor. The (possibly modified) response returned by + `post_get_app_version` will be passed to + `post_get_app_version_with_metadata`. + """ + return response, metadata + + def pre_get_changelog( + self, + request: agent_service.GetChangelogRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.GetChangelogRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_changelog + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_get_changelog(self, response: changelog.Changelog) -> changelog.Changelog: + """Post-rpc interceptor for get_changelog + + DEPRECATED. Please use the `post_get_changelog_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_get_changelog` interceptor runs + before the `post_get_changelog_with_metadata` interceptor. + """ + return response + + def post_get_changelog_with_metadata( + self, + response: changelog.Changelog, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[changelog.Changelog, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_changelog + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_get_changelog_with_metadata` + interceptor in new development instead of the `post_get_changelog` interceptor. + When both interceptors are used, this `post_get_changelog_with_metadata` interceptor runs after the + `post_get_changelog` interceptor. The (possibly modified) response returned by + `post_get_changelog` will be passed to + `post_get_changelog_with_metadata`. + """ + return response, metadata + + def pre_get_conversation( + self, + request: agent_service.GetConversationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.GetConversationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_conversation + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_get_conversation( + self, response: conversation.Conversation + ) -> conversation.Conversation: + """Post-rpc interceptor for get_conversation + + DEPRECATED. Please use the `post_get_conversation_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_get_conversation` interceptor runs + before the `post_get_conversation_with_metadata` interceptor. + """ + return response + + def post_get_conversation_with_metadata( + self, + response: conversation.Conversation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[conversation.Conversation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_conversation + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_get_conversation_with_metadata` + interceptor in new development instead of the `post_get_conversation` interceptor. + When both interceptors are used, this `post_get_conversation_with_metadata` interceptor runs after the + `post_get_conversation` interceptor. The (possibly modified) response returned by + `post_get_conversation` will be passed to + `post_get_conversation_with_metadata`. + """ + return response, metadata + + def pre_get_deployment( + self, + request: agent_service.GetDeploymentRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.GetDeploymentRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_deployment + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_get_deployment( + self, response: deployment.Deployment + ) -> deployment.Deployment: + """Post-rpc interceptor for get_deployment + + DEPRECATED. Please use the `post_get_deployment_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_get_deployment` interceptor runs + before the `post_get_deployment_with_metadata` interceptor. + """ + return response + + def post_get_deployment_with_metadata( + self, + response: deployment.Deployment, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[deployment.Deployment, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_deployment + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_get_deployment_with_metadata` + interceptor in new development instead of the `post_get_deployment` interceptor. + When both interceptors are used, this `post_get_deployment_with_metadata` interceptor runs after the + `post_get_deployment` interceptor. The (possibly modified) response returned by + `post_get_deployment` will be passed to + `post_get_deployment_with_metadata`. + """ + return response, metadata + + def pre_get_example( + self, + request: agent_service.GetExampleRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.GetExampleRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_example + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_get_example(self, response: example.Example) -> example.Example: + """Post-rpc interceptor for get_example + + DEPRECATED. Please use the `post_get_example_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_get_example` interceptor runs + before the `post_get_example_with_metadata` interceptor. + """ + return response + + def post_get_example_with_metadata( + self, + response: example.Example, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[example.Example, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_example + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_get_example_with_metadata` + interceptor in new development instead of the `post_get_example` interceptor. + When both interceptors are used, this `post_get_example_with_metadata` interceptor runs after the + `post_get_example` interceptor. The (possibly modified) response returned by + `post_get_example` will be passed to + `post_get_example_with_metadata`. + """ + return response, metadata + + def pre_get_guardrail( + self, + request: agent_service.GetGuardrailRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.GetGuardrailRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_guardrail + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_get_guardrail(self, response: guardrail.Guardrail) -> guardrail.Guardrail: + """Post-rpc interceptor for get_guardrail + + DEPRECATED. Please use the `post_get_guardrail_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_get_guardrail` interceptor runs + before the `post_get_guardrail_with_metadata` interceptor. + """ + return response + + def post_get_guardrail_with_metadata( + self, + response: guardrail.Guardrail, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[guardrail.Guardrail, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_guardrail + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_get_guardrail_with_metadata` + interceptor in new development instead of the `post_get_guardrail` interceptor. + When both interceptors are used, this `post_get_guardrail_with_metadata` interceptor runs after the + `post_get_guardrail` interceptor. The (possibly modified) response returned by + `post_get_guardrail` will be passed to + `post_get_guardrail_with_metadata`. + """ + return response, metadata + + def pre_get_tool( + self, + request: agent_service.GetToolRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[agent_service.GetToolRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_tool + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_get_tool(self, response: tool.Tool) -> tool.Tool: + """Post-rpc interceptor for get_tool + + DEPRECATED. Please use the `post_get_tool_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_get_tool` interceptor runs + before the `post_get_tool_with_metadata` interceptor. + """ + return response + + def post_get_tool_with_metadata( + self, response: tool.Tool, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[tool.Tool, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_tool + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_get_tool_with_metadata` + interceptor in new development instead of the `post_get_tool` interceptor. + When both interceptors are used, this `post_get_tool_with_metadata` interceptor runs after the + `post_get_tool` interceptor. The (possibly modified) response returned by + `post_get_tool` will be passed to + `post_get_tool_with_metadata`. + """ + return response, metadata + + def pre_get_toolset( + self, + request: agent_service.GetToolsetRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.GetToolsetRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_toolset + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_get_toolset(self, response: toolset.Toolset) -> toolset.Toolset: + """Post-rpc interceptor for get_toolset + + DEPRECATED. Please use the `post_get_toolset_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_get_toolset` interceptor runs + before the `post_get_toolset_with_metadata` interceptor. + """ + return response + + def post_get_toolset_with_metadata( + self, + response: toolset.Toolset, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[toolset.Toolset, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_toolset + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_get_toolset_with_metadata` + interceptor in new development instead of the `post_get_toolset` interceptor. + When both interceptors are used, this `post_get_toolset_with_metadata` interceptor runs after the + `post_get_toolset` interceptor. The (possibly modified) response returned by + `post_get_toolset` will be passed to + `post_get_toolset_with_metadata`. + """ + return response, metadata + + def pre_import_app( + self, + request: agent_service.ImportAppRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[agent_service.ImportAppRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for import_app + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_import_app( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for import_app + + DEPRECATED. Please use the `post_import_app_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_import_app` interceptor runs + before the `post_import_app_with_metadata` interceptor. + """ + return response + + def post_import_app_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for import_app + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_import_app_with_metadata` + interceptor in new development instead of the `post_import_app` interceptor. + When both interceptors are used, this `post_import_app_with_metadata` interceptor runs after the + `post_import_app` interceptor. The (possibly modified) response returned by + `post_import_app` will be passed to + `post_import_app_with_metadata`. + """ + return response, metadata + + def pre_list_agents( + self, + request: agent_service.ListAgentsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.ListAgentsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_agents + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_list_agents( + self, response: agent_service.ListAgentsResponse + ) -> agent_service.ListAgentsResponse: + """Post-rpc interceptor for list_agents + + DEPRECATED. Please use the `post_list_agents_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_list_agents` interceptor runs + before the `post_list_agents_with_metadata` interceptor. + """ + return response + + def post_list_agents_with_metadata( + self, + response: agent_service.ListAgentsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.ListAgentsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_agents + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_list_agents_with_metadata` + interceptor in new development instead of the `post_list_agents` interceptor. + When both interceptors are used, this `post_list_agents_with_metadata` interceptor runs after the + `post_list_agents` interceptor. The (possibly modified) response returned by + `post_list_agents` will be passed to + `post_list_agents_with_metadata`. + """ + return response, metadata + + def pre_list_apps( + self, + request: agent_service.ListAppsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[agent_service.ListAppsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_apps + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_list_apps( + self, response: agent_service.ListAppsResponse + ) -> agent_service.ListAppsResponse: + """Post-rpc interceptor for list_apps + + DEPRECATED. Please use the `post_list_apps_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_list_apps` interceptor runs + before the `post_list_apps_with_metadata` interceptor. + """ + return response + + def post_list_apps_with_metadata( + self, + response: agent_service.ListAppsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[agent_service.ListAppsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_apps + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_list_apps_with_metadata` + interceptor in new development instead of the `post_list_apps` interceptor. + When both interceptors are used, this `post_list_apps_with_metadata` interceptor runs after the + `post_list_apps` interceptor. The (possibly modified) response returned by + `post_list_apps` will be passed to + `post_list_apps_with_metadata`. + """ + return response, metadata + + def pre_list_app_versions( + self, + request: agent_service.ListAppVersionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.ListAppVersionsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_app_versions + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_list_app_versions( + self, response: agent_service.ListAppVersionsResponse + ) -> agent_service.ListAppVersionsResponse: + """Post-rpc interceptor for list_app_versions + + DEPRECATED. Please use the `post_list_app_versions_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_list_app_versions` interceptor runs + before the `post_list_app_versions_with_metadata` interceptor. + """ + return response + + def post_list_app_versions_with_metadata( + self, + response: agent_service.ListAppVersionsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.ListAppVersionsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_app_versions + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_list_app_versions_with_metadata` + interceptor in new development instead of the `post_list_app_versions` interceptor. + When both interceptors are used, this `post_list_app_versions_with_metadata` interceptor runs after the + `post_list_app_versions` interceptor. The (possibly modified) response returned by + `post_list_app_versions` will be passed to + `post_list_app_versions_with_metadata`. + """ + return response, metadata + + def pre_list_changelogs( + self, + request: agent_service.ListChangelogsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.ListChangelogsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_changelogs + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_list_changelogs( + self, response: agent_service.ListChangelogsResponse + ) -> agent_service.ListChangelogsResponse: + """Post-rpc interceptor for list_changelogs + + DEPRECATED. Please use the `post_list_changelogs_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_list_changelogs` interceptor runs + before the `post_list_changelogs_with_metadata` interceptor. + """ + return response + + def post_list_changelogs_with_metadata( + self, + response: agent_service.ListChangelogsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.ListChangelogsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_changelogs + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_list_changelogs_with_metadata` + interceptor in new development instead of the `post_list_changelogs` interceptor. + When both interceptors are used, this `post_list_changelogs_with_metadata` interceptor runs after the + `post_list_changelogs` interceptor. The (possibly modified) response returned by + `post_list_changelogs` will be passed to + `post_list_changelogs_with_metadata`. + """ + return response, metadata + + def pre_list_conversations( + self, + request: agent_service.ListConversationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.ListConversationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_conversations + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_list_conversations( + self, response: agent_service.ListConversationsResponse + ) -> agent_service.ListConversationsResponse: + """Post-rpc interceptor for list_conversations + + DEPRECATED. Please use the `post_list_conversations_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_list_conversations` interceptor runs + before the `post_list_conversations_with_metadata` interceptor. + """ + return response + + def post_list_conversations_with_metadata( + self, + response: agent_service.ListConversationsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.ListConversationsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_conversations + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_list_conversations_with_metadata` + interceptor in new development instead of the `post_list_conversations` interceptor. + When both interceptors are used, this `post_list_conversations_with_metadata` interceptor runs after the + `post_list_conversations` interceptor. The (possibly modified) response returned by + `post_list_conversations` will be passed to + `post_list_conversations_with_metadata`. + """ + return response, metadata + + def pre_list_deployments( + self, + request: agent_service.ListDeploymentsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.ListDeploymentsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_deployments + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_list_deployments( + self, response: agent_service.ListDeploymentsResponse + ) -> agent_service.ListDeploymentsResponse: + """Post-rpc interceptor for list_deployments + + DEPRECATED. Please use the `post_list_deployments_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_list_deployments` interceptor runs + before the `post_list_deployments_with_metadata` interceptor. + """ + return response + + def post_list_deployments_with_metadata( + self, + response: agent_service.ListDeploymentsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.ListDeploymentsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_deployments + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_list_deployments_with_metadata` + interceptor in new development instead of the `post_list_deployments` interceptor. + When both interceptors are used, this `post_list_deployments_with_metadata` interceptor runs after the + `post_list_deployments` interceptor. The (possibly modified) response returned by + `post_list_deployments` will be passed to + `post_list_deployments_with_metadata`. + """ + return response, metadata + + def pre_list_examples( + self, + request: agent_service.ListExamplesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.ListExamplesRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_examples + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_list_examples( + self, response: agent_service.ListExamplesResponse + ) -> agent_service.ListExamplesResponse: + """Post-rpc interceptor for list_examples + + DEPRECATED. Please use the `post_list_examples_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_list_examples` interceptor runs + before the `post_list_examples_with_metadata` interceptor. + """ + return response + + def post_list_examples_with_metadata( + self, + response: agent_service.ListExamplesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.ListExamplesResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_examples + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_list_examples_with_metadata` + interceptor in new development instead of the `post_list_examples` interceptor. + When both interceptors are used, this `post_list_examples_with_metadata` interceptor runs after the + `post_list_examples` interceptor. The (possibly modified) response returned by + `post_list_examples` will be passed to + `post_list_examples_with_metadata`. + """ + return response, metadata + + def pre_list_guardrails( + self, + request: agent_service.ListGuardrailsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.ListGuardrailsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_guardrails + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_list_guardrails( + self, response: agent_service.ListGuardrailsResponse + ) -> agent_service.ListGuardrailsResponse: + """Post-rpc interceptor for list_guardrails + + DEPRECATED. Please use the `post_list_guardrails_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_list_guardrails` interceptor runs + before the `post_list_guardrails_with_metadata` interceptor. + """ + return response + + def post_list_guardrails_with_metadata( + self, + response: agent_service.ListGuardrailsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.ListGuardrailsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_guardrails + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_list_guardrails_with_metadata` + interceptor in new development instead of the `post_list_guardrails` interceptor. + When both interceptors are used, this `post_list_guardrails_with_metadata` interceptor runs after the + `post_list_guardrails` interceptor. The (possibly modified) response returned by + `post_list_guardrails` will be passed to + `post_list_guardrails_with_metadata`. + """ + return response, metadata + + def pre_list_tools( + self, + request: agent_service.ListToolsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[agent_service.ListToolsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_tools + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_list_tools( + self, response: agent_service.ListToolsResponse + ) -> agent_service.ListToolsResponse: + """Post-rpc interceptor for list_tools + + DEPRECATED. Please use the `post_list_tools_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_list_tools` interceptor runs + before the `post_list_tools_with_metadata` interceptor. + """ + return response + + def post_list_tools_with_metadata( + self, + response: agent_service.ListToolsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.ListToolsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_tools + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_list_tools_with_metadata` + interceptor in new development instead of the `post_list_tools` interceptor. + When both interceptors are used, this `post_list_tools_with_metadata` interceptor runs after the + `post_list_tools` interceptor. The (possibly modified) response returned by + `post_list_tools` will be passed to + `post_list_tools_with_metadata`. + """ + return response, metadata + + def pre_list_toolsets( + self, + request: agent_service.ListToolsetsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.ListToolsetsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_toolsets + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_list_toolsets( + self, response: agent_service.ListToolsetsResponse + ) -> agent_service.ListToolsetsResponse: + """Post-rpc interceptor for list_toolsets + + DEPRECATED. Please use the `post_list_toolsets_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_list_toolsets` interceptor runs + before the `post_list_toolsets_with_metadata` interceptor. + """ + return response + + def post_list_toolsets_with_metadata( + self, + response: agent_service.ListToolsetsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.ListToolsetsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_toolsets + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_list_toolsets_with_metadata` + interceptor in new development instead of the `post_list_toolsets` interceptor. + When both interceptors are used, this `post_list_toolsets_with_metadata` interceptor runs after the + `post_list_toolsets` interceptor. The (possibly modified) response returned by + `post_list_toolsets` will be passed to + `post_list_toolsets_with_metadata`. + """ + return response, metadata + + def pre_restore_app_version( + self, + request: agent_service.RestoreAppVersionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.RestoreAppVersionRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for restore_app_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_restore_app_version( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for restore_app_version + + DEPRECATED. Please use the `post_restore_app_version_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_restore_app_version` interceptor runs + before the `post_restore_app_version_with_metadata` interceptor. + """ + return response + + def post_restore_app_version_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for restore_app_version + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_restore_app_version_with_metadata` + interceptor in new development instead of the `post_restore_app_version` interceptor. + When both interceptors are used, this `post_restore_app_version_with_metadata` interceptor runs after the + `post_restore_app_version` interceptor. The (possibly modified) response returned by + `post_restore_app_version` will be passed to + `post_restore_app_version_with_metadata`. + """ + return response, metadata + + def pre_update_agent( + self, + request: agent_service.UpdateAgentRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.UpdateAgentRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_agent + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_update_agent(self, response: gcc_agent.Agent) -> gcc_agent.Agent: + """Post-rpc interceptor for update_agent + + DEPRECATED. Please use the `post_update_agent_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_update_agent` interceptor runs + before the `post_update_agent_with_metadata` interceptor. + """ + return response + + def post_update_agent_with_metadata( + self, + response: gcc_agent.Agent, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gcc_agent.Agent, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_agent + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_update_agent_with_metadata` + interceptor in new development instead of the `post_update_agent` interceptor. + When both interceptors are used, this `post_update_agent_with_metadata` interceptor runs after the + `post_update_agent` interceptor. The (possibly modified) response returned by + `post_update_agent` will be passed to + `post_update_agent_with_metadata`. + """ + return response, metadata + + def pre_update_app( + self, + request: agent_service.UpdateAppRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[agent_service.UpdateAppRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_app + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_update_app(self, response: gcc_app.App) -> gcc_app.App: + """Post-rpc interceptor for update_app + + DEPRECATED. Please use the `post_update_app_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_update_app` interceptor runs + before the `post_update_app_with_metadata` interceptor. + """ + return response + + def post_update_app_with_metadata( + self, response: gcc_app.App, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[gcc_app.App, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_app + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_update_app_with_metadata` + interceptor in new development instead of the `post_update_app` interceptor. + When both interceptors are used, this `post_update_app_with_metadata` interceptor runs after the + `post_update_app` interceptor. The (possibly modified) response returned by + `post_update_app` will be passed to + `post_update_app_with_metadata`. + """ + return response, metadata + + def pre_update_deployment( + self, + request: agent_service.UpdateDeploymentRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.UpdateDeploymentRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_deployment + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_update_deployment( + self, response: gcc_deployment.Deployment + ) -> gcc_deployment.Deployment: + """Post-rpc interceptor for update_deployment + + DEPRECATED. Please use the `post_update_deployment_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_update_deployment` interceptor runs + before the `post_update_deployment_with_metadata` interceptor. + """ + return response + + def post_update_deployment_with_metadata( + self, + response: gcc_deployment.Deployment, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gcc_deployment.Deployment, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_deployment + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_update_deployment_with_metadata` + interceptor in new development instead of the `post_update_deployment` interceptor. + When both interceptors are used, this `post_update_deployment_with_metadata` interceptor runs after the + `post_update_deployment` interceptor. The (possibly modified) response returned by + `post_update_deployment` will be passed to + `post_update_deployment_with_metadata`. + """ + return response, metadata + + def pre_update_example( + self, + request: agent_service.UpdateExampleRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.UpdateExampleRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_example + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_update_example(self, response: gcc_example.Example) -> gcc_example.Example: + """Post-rpc interceptor for update_example + + DEPRECATED. Please use the `post_update_example_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_update_example` interceptor runs + before the `post_update_example_with_metadata` interceptor. + """ + return response + + def post_update_example_with_metadata( + self, + response: gcc_example.Example, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gcc_example.Example, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_example + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_update_example_with_metadata` + interceptor in new development instead of the `post_update_example` interceptor. + When both interceptors are used, this `post_update_example_with_metadata` interceptor runs after the + `post_update_example` interceptor. The (possibly modified) response returned by + `post_update_example` will be passed to + `post_update_example_with_metadata`. + """ + return response, metadata + + def pre_update_guardrail( + self, + request: agent_service.UpdateGuardrailRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.UpdateGuardrailRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_guardrail + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_update_guardrail( + self, response: gcc_guardrail.Guardrail + ) -> gcc_guardrail.Guardrail: + """Post-rpc interceptor for update_guardrail + + DEPRECATED. Please use the `post_update_guardrail_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_update_guardrail` interceptor runs + before the `post_update_guardrail_with_metadata` interceptor. + """ + return response + + def post_update_guardrail_with_metadata( + self, + response: gcc_guardrail.Guardrail, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gcc_guardrail.Guardrail, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_guardrail + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_update_guardrail_with_metadata` + interceptor in new development instead of the `post_update_guardrail` interceptor. + When both interceptors are used, this `post_update_guardrail_with_metadata` interceptor runs after the + `post_update_guardrail` interceptor. The (possibly modified) response returned by + `post_update_guardrail` will be passed to + `post_update_guardrail_with_metadata`. + """ + return response, metadata + + def pre_update_tool( + self, + request: agent_service.UpdateToolRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.UpdateToolRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_tool + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_update_tool(self, response: gcc_tool.Tool) -> gcc_tool.Tool: + """Post-rpc interceptor for update_tool + + DEPRECATED. Please use the `post_update_tool_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_update_tool` interceptor runs + before the `post_update_tool_with_metadata` interceptor. + """ + return response + + def post_update_tool_with_metadata( + self, response: gcc_tool.Tool, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[gcc_tool.Tool, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_tool + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_update_tool_with_metadata` + interceptor in new development instead of the `post_update_tool` interceptor. + When both interceptors are used, this `post_update_tool_with_metadata` interceptor runs after the + `post_update_tool` interceptor. The (possibly modified) response returned by + `post_update_tool` will be passed to + `post_update_tool_with_metadata`. + """ + return response, metadata + + def pre_update_toolset( + self, + request: agent_service.UpdateToolsetRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + agent_service.UpdateToolsetRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_toolset + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_update_toolset(self, response: gcc_toolset.Toolset) -> gcc_toolset.Toolset: + """Post-rpc interceptor for update_toolset + + DEPRECATED. Please use the `post_update_toolset_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. This `post_update_toolset` interceptor runs + before the `post_update_toolset_with_metadata` interceptor. + """ + return response + + def post_update_toolset_with_metadata( + self, + response: gcc_toolset.Toolset, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gcc_toolset.Toolset, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_toolset + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AgentService server but before it is returned to user code. + + We recommend only using this `post_update_toolset_with_metadata` + interceptor in new development instead of the `post_update_toolset` interceptor. + When both interceptors are used, this `post_update_toolset_with_metadata` interceptor runs after the + `post_update_toolset` interceptor. The (possibly modified) response returned by + `post_update_toolset` will be passed to + `post_update_toolset_with_metadata`. + """ + return response, metadata + + def pre_get_location( + self, + request: locations_pb2.GetLocationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.Location + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. + """ + return response + + def pre_list_locations( + self, + request: locations_pb2.ListLocationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsResponse + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_cancel_operation(self, response: None) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. + """ + return response + + def pre_delete_operation( + self, + request: operations_pb2.DeleteOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_delete_operation(self, response: None) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the AgentService server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the AgentService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class AgentServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AgentServiceRestInterceptor + + +class AgentServiceRestTransport(_BaseAgentServiceRestTransport): + """REST backend synchronous transport for AgentService. + + The service that manages agent-related resources in Gemini + Enterprise for Customer Engagement (CES). + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "ces.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[AgentServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'ces.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or AgentServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.CancelOperation": [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ], + "google.longrunning.Operations.DeleteOperation": [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*}/operations", + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1beta", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _BatchDeleteConversations( + _BaseAgentServiceRestTransport._BaseBatchDeleteConversations, + AgentServiceRestStub, + ): + def __hash__(self): + return hash("AgentServiceRestTransport.BatchDeleteConversations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: agent_service.BatchDeleteConversationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the batch delete + conversations method over HTTP. + + Args: + request (~.agent_service.BatchDeleteConversationsRequest): + The request object. Request message for + [AgentService.BatchDeleteConversations][google.cloud.ces.v1beta.AgentService.BatchDeleteConversations]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseAgentServiceRestTransport._BaseBatchDeleteConversations._get_http_options() + + request, metadata = self._interceptor.pre_batch_delete_conversations( + request, metadata + ) + transcoded_request = _BaseAgentServiceRestTransport._BaseBatchDeleteConversations._get_transcoded_request( + http_options, request + ) + + body = _BaseAgentServiceRestTransport._BaseBatchDeleteConversations._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseAgentServiceRestTransport._BaseBatchDeleteConversations._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.BatchDeleteConversations", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "BatchDeleteConversations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + AgentServiceRestTransport._BatchDeleteConversations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_batch_delete_conversations(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_batch_delete_conversations_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.batch_delete_conversations", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "BatchDeleteConversations", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateAgent( + _BaseAgentServiceRestTransport._BaseCreateAgent, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.CreateAgent") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: agent_service.CreateAgentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_agent.Agent: + r"""Call the create agent method over HTTP. + + Args: + request (~.agent_service.CreateAgentRequest): + The request object. Request message for + [AgentService.CreateAgent][google.cloud.ces.v1beta.AgentService.CreateAgent]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gcc_agent.Agent: + An agent acts as the fundamental + building block that provides + instructions to the Large Language Model + (LLM) for executing specific tasks. + + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseCreateAgent._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_agent(request, metadata) + transcoded_request = ( + _BaseAgentServiceRestTransport._BaseCreateAgent._get_transcoded_request( + http_options, request + ) + ) + + body = ( + _BaseAgentServiceRestTransport._BaseCreateAgent._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseAgentServiceRestTransport._BaseCreateAgent._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.CreateAgent", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "CreateAgent", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._CreateAgent._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcc_agent.Agent() + pb_resp = gcc_agent.Agent.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_agent(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_agent_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gcc_agent.Agent.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.create_agent", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "CreateAgent", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateApp( + _BaseAgentServiceRestTransport._BaseCreateApp, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.CreateApp") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: agent_service.CreateAppRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create app method over HTTP. + + Args: + request (~.agent_service.CreateAppRequest): + The request object. Request message for + [AgentService.CreateApp][google.cloud.ces.v1beta.AgentService.CreateApp]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseCreateApp._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_app(request, metadata) + transcoded_request = ( + _BaseAgentServiceRestTransport._BaseCreateApp._get_transcoded_request( + http_options, request + ) + ) + + body = _BaseAgentServiceRestTransport._BaseCreateApp._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BaseAgentServiceRestTransport._BaseCreateApp._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.CreateApp", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "CreateApp", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._CreateApp._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_app(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_app_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.create_app", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "CreateApp", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateAppVersion( + _BaseAgentServiceRestTransport._BaseCreateAppVersion, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.CreateAppVersion") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: agent_service.CreateAppVersionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_app_version.AppVersion: + r"""Call the create app version method over HTTP. + + Args: + request (~.agent_service.CreateAppVersionRequest): + The request object. Request message for + [AgentService.CreateAppVersion][google.cloud.ces.v1beta.AgentService.CreateAppVersion] + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gcc_app_version.AppVersion: + In Customer Engagement Suite (CES), + an app version is a snapshot of the app + at a specific point in time. It is + immutable and cannot be modified once + created. + + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseCreateAppVersion._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_app_version( + request, metadata + ) + transcoded_request = _BaseAgentServiceRestTransport._BaseCreateAppVersion._get_transcoded_request( + http_options, request + ) + + body = _BaseAgentServiceRestTransport._BaseCreateAppVersion._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseAgentServiceRestTransport._BaseCreateAppVersion._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.CreateAppVersion", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "CreateAppVersion", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._CreateAppVersion._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcc_app_version.AppVersion() + pb_resp = gcc_app_version.AppVersion.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_app_version(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_app_version_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gcc_app_version.AppVersion.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.create_app_version", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "CreateAppVersion", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateDeployment( + _BaseAgentServiceRestTransport._BaseCreateDeployment, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.CreateDeployment") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: agent_service.CreateDeploymentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_deployment.Deployment: + r"""Call the create deployment method over HTTP. + + Args: + request (~.agent_service.CreateDeploymentRequest): + The request object. Request message for + [AgentService.CreateDeployment][google.cloud.ces.v1beta.AgentService.CreateDeployment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gcc_deployment.Deployment: + A deployment represents an immutable, + queryable version of the app. It is used + to deploy an app version with a specific + channel profile. + + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseCreateDeployment._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_deployment( + request, metadata + ) + transcoded_request = _BaseAgentServiceRestTransport._BaseCreateDeployment._get_transcoded_request( + http_options, request + ) + + body = _BaseAgentServiceRestTransport._BaseCreateDeployment._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseAgentServiceRestTransport._BaseCreateDeployment._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.CreateDeployment", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "CreateDeployment", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._CreateDeployment._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcc_deployment.Deployment() + pb_resp = gcc_deployment.Deployment.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_deployment(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_deployment_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gcc_deployment.Deployment.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.create_deployment", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "CreateDeployment", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateExample( + _BaseAgentServiceRestTransport._BaseCreateExample, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.CreateExample") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: agent_service.CreateExampleRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_example.Example: + r"""Call the create example method over HTTP. + + Args: + request (~.agent_service.CreateExampleRequest): + The request object. Request message for + [AgentService.CreateExample][google.cloud.ces.v1beta.AgentService.CreateExample]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gcc_example.Example: + An example represents a sample + conversation between the user and the + agent(s). + + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseCreateExample._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_example(request, metadata) + transcoded_request = _BaseAgentServiceRestTransport._BaseCreateExample._get_transcoded_request( + http_options, request + ) + + body = _BaseAgentServiceRestTransport._BaseCreateExample._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseAgentServiceRestTransport._BaseCreateExample._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.CreateExample", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "CreateExample", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._CreateExample._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcc_example.Example() + pb_resp = gcc_example.Example.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_example(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_example_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gcc_example.Example.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.create_example", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "CreateExample", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateGuardrail( + _BaseAgentServiceRestTransport._BaseCreateGuardrail, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.CreateGuardrail") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: agent_service.CreateGuardrailRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_guardrail.Guardrail: + r"""Call the create guardrail method over HTTP. + + Args: + request (~.agent_service.CreateGuardrailRequest): + The request object. Request message for + [AgentService.CreateGuardrail][google.cloud.ces.v1beta.AgentService.CreateGuardrail]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gcc_guardrail.Guardrail: + Guardrail contains a list of checks + and balances to keep the agents safe and + secure. + + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseCreateGuardrail._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_guardrail( + request, metadata + ) + transcoded_request = _BaseAgentServiceRestTransport._BaseCreateGuardrail._get_transcoded_request( + http_options, request + ) + + body = _BaseAgentServiceRestTransport._BaseCreateGuardrail._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseAgentServiceRestTransport._BaseCreateGuardrail._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.CreateGuardrail", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "CreateGuardrail", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._CreateGuardrail._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcc_guardrail.Guardrail() + pb_resp = gcc_guardrail.Guardrail.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_guardrail(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_guardrail_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gcc_guardrail.Guardrail.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.create_guardrail", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "CreateGuardrail", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateTool( + _BaseAgentServiceRestTransport._BaseCreateTool, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.CreateTool") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: agent_service.CreateToolRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_tool.Tool: + r"""Call the create tool method over HTTP. + + Args: + request (~.agent_service.CreateToolRequest): + The request object. Request message for + [AgentService.CreateTool][google.cloud.ces.v1beta.AgentService.CreateTool]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gcc_tool.Tool: + A tool represents an action that the + CES agent can take to achieve certain + goals. + + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseCreateTool._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_tool(request, metadata) + transcoded_request = ( + _BaseAgentServiceRestTransport._BaseCreateTool._get_transcoded_request( + http_options, request + ) + ) + + body = ( + _BaseAgentServiceRestTransport._BaseCreateTool._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseAgentServiceRestTransport._BaseCreateTool._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.CreateTool", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "CreateTool", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._CreateTool._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcc_tool.Tool() + pb_resp = gcc_tool.Tool.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_tool(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_tool_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gcc_tool.Tool.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.create_tool", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "CreateTool", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateToolset( + _BaseAgentServiceRestTransport._BaseCreateToolset, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.CreateToolset") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: agent_service.CreateToolsetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_toolset.Toolset: + r"""Call the create toolset method over HTTP. + + Args: + request (~.agent_service.CreateToolsetRequest): + The request object. Request message for + [AgentService.CreateToolset][google.cloud.ces.v1beta.AgentService.CreateToolset]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gcc_toolset.Toolset: + A toolset represents a group of + dynamically managed tools that can be + used by the agent. + + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseCreateToolset._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_toolset(request, metadata) + transcoded_request = _BaseAgentServiceRestTransport._BaseCreateToolset._get_transcoded_request( + http_options, request + ) + + body = _BaseAgentServiceRestTransport._BaseCreateToolset._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseAgentServiceRestTransport._BaseCreateToolset._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.CreateToolset", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "CreateToolset", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._CreateToolset._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcc_toolset.Toolset() + pb_resp = gcc_toolset.Toolset.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_toolset(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_toolset_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gcc_toolset.Toolset.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.create_toolset", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "CreateToolset", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteAgent( + _BaseAgentServiceRestTransport._BaseDeleteAgent, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.DeleteAgent") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: agent_service.DeleteAgentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete agent method over HTTP. + + Args: + request (~.agent_service.DeleteAgentRequest): + The request object. Request message for + [AgentService.DeleteAgent][google.cloud.ces.v1beta.AgentService.DeleteAgent]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseDeleteAgent._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_agent(request, metadata) + transcoded_request = ( + _BaseAgentServiceRestTransport._BaseDeleteAgent._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseAgentServiceRestTransport._BaseDeleteAgent._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.DeleteAgent", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "DeleteAgent", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._DeleteAgent._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteApp( + _BaseAgentServiceRestTransport._BaseDeleteApp, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.DeleteApp") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: agent_service.DeleteAppRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete app method over HTTP. + + Args: + request (~.agent_service.DeleteAppRequest): + The request object. Request message for + [AgentService.DeleteApp][google.cloud.ces.v1beta.AgentService.DeleteApp]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseDeleteApp._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_app(request, metadata) + transcoded_request = ( + _BaseAgentServiceRestTransport._BaseDeleteApp._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseAgentServiceRestTransport._BaseDeleteApp._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.DeleteApp", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "DeleteApp", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._DeleteApp._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_app(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_app_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.delete_app", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "DeleteApp", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteAppVersion( + _BaseAgentServiceRestTransport._BaseDeleteAppVersion, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.DeleteAppVersion") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: agent_service.DeleteAppVersionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete app version method over HTTP. + + Args: + request (~.agent_service.DeleteAppVersionRequest): + The request object. Request message for + [AgentService.DeleteAppVersion][google.cloud.ces.v1beta.AgentService.DeleteAppVersion]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseDeleteAppVersion._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_app_version( + request, metadata + ) + transcoded_request = _BaseAgentServiceRestTransport._BaseDeleteAppVersion._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseAgentServiceRestTransport._BaseDeleteAppVersion._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.DeleteAppVersion", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "DeleteAppVersion", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._DeleteAppVersion._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteConversation( + _BaseAgentServiceRestTransport._BaseDeleteConversation, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.DeleteConversation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: agent_service.DeleteConversationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete conversation method over HTTP. + + Args: + request (~.agent_service.DeleteConversationRequest): + The request object. Request message for + [AgentService.DeleteConversation][google.cloud.ces.v1beta.AgentService.DeleteConversation]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseAgentServiceRestTransport._BaseDeleteConversation._get_http_options() + + request, metadata = self._interceptor.pre_delete_conversation( + request, metadata + ) + transcoded_request = _BaseAgentServiceRestTransport._BaseDeleteConversation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseAgentServiceRestTransport._BaseDeleteConversation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.DeleteConversation", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "DeleteConversation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._DeleteConversation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteDeployment( + _BaseAgentServiceRestTransport._BaseDeleteDeployment, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.DeleteDeployment") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: agent_service.DeleteDeploymentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete deployment method over HTTP. + + Args: + request (~.agent_service.DeleteDeploymentRequest): + The request object. Request message for + [AgentService.DeleteDeployment][google.cloud.ces.v1beta.AgentService.DeleteDeployment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseDeleteDeployment._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_deployment( + request, metadata + ) + transcoded_request = _BaseAgentServiceRestTransport._BaseDeleteDeployment._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseAgentServiceRestTransport._BaseDeleteDeployment._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.DeleteDeployment", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "DeleteDeployment", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._DeleteDeployment._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteExample( + _BaseAgentServiceRestTransport._BaseDeleteExample, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.DeleteExample") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: agent_service.DeleteExampleRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete example method over HTTP. + + Args: + request (~.agent_service.DeleteExampleRequest): + The request object. Request message for + [AgentService.DeleteExample][google.cloud.ces.v1beta.AgentService.DeleteExample]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseDeleteExample._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_example(request, metadata) + transcoded_request = _BaseAgentServiceRestTransport._BaseDeleteExample._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseAgentServiceRestTransport._BaseDeleteExample._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.DeleteExample", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "DeleteExample", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._DeleteExample._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteGuardrail( + _BaseAgentServiceRestTransport._BaseDeleteGuardrail, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.DeleteGuardrail") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: agent_service.DeleteGuardrailRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete guardrail method over HTTP. + + Args: + request (~.agent_service.DeleteGuardrailRequest): + The request object. Request message for + [AgentService.DeleteGuardrail][google.cloud.ces.v1beta.AgentService.DeleteGuardrail]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseDeleteGuardrail._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_guardrail( + request, metadata + ) + transcoded_request = _BaseAgentServiceRestTransport._BaseDeleteGuardrail._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseAgentServiceRestTransport._BaseDeleteGuardrail._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.DeleteGuardrail", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "DeleteGuardrail", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._DeleteGuardrail._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteTool( + _BaseAgentServiceRestTransport._BaseDeleteTool, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.DeleteTool") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: agent_service.DeleteToolRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete tool method over HTTP. + + Args: + request (~.agent_service.DeleteToolRequest): + The request object. Request message for + [AgentService.DeleteTool][google.cloud.ces.v1beta.AgentService.DeleteTool]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseDeleteTool._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_tool(request, metadata) + transcoded_request = ( + _BaseAgentServiceRestTransport._BaseDeleteTool._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseAgentServiceRestTransport._BaseDeleteTool._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.DeleteTool", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "DeleteTool", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._DeleteTool._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteToolset( + _BaseAgentServiceRestTransport._BaseDeleteToolset, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.DeleteToolset") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: agent_service.DeleteToolsetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete toolset method over HTTP. + + Args: + request (~.agent_service.DeleteToolsetRequest): + The request object. Request message for + [AgentService.DeleteToolset][google.cloud.ces.v1beta.AgentService.DeleteToolset]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseDeleteToolset._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_toolset(request, metadata) + transcoded_request = _BaseAgentServiceRestTransport._BaseDeleteToolset._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseAgentServiceRestTransport._BaseDeleteToolset._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.DeleteToolset", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "DeleteToolset", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._DeleteToolset._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _ExportApp( + _BaseAgentServiceRestTransport._BaseExportApp, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.ExportApp") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: agent_service.ExportAppRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the export app method over HTTP. + + Args: + request (~.agent_service.ExportAppRequest): + The request object. Request message for + [AgentService.ExportApp][google.cloud.ces.v1beta.AgentService.ExportApp]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseExportApp._get_http_options() + ) + + request, metadata = self._interceptor.pre_export_app(request, metadata) + transcoded_request = ( + _BaseAgentServiceRestTransport._BaseExportApp._get_transcoded_request( + http_options, request + ) + ) + + body = _BaseAgentServiceRestTransport._BaseExportApp._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BaseAgentServiceRestTransport._BaseExportApp._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.ExportApp", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "ExportApp", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._ExportApp._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_export_app(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_export_app_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.export_app", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "ExportApp", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetAgent(_BaseAgentServiceRestTransport._BaseGetAgent, AgentServiceRestStub): + def __hash__(self): + return hash("AgentServiceRestTransport.GetAgent") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: agent_service.GetAgentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> agent.Agent: + r"""Call the get agent method over HTTP. + + Args: + request (~.agent_service.GetAgentRequest): + The request object. Request message for + [AgentService.GetAgent][google.cloud.ces.v1beta.AgentService.GetAgent]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.agent.Agent: + An agent acts as the fundamental + building block that provides + instructions to the Large Language Model + (LLM) for executing specific tasks. + + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseGetAgent._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_agent(request, metadata) + transcoded_request = ( + _BaseAgentServiceRestTransport._BaseGetAgent._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseAgentServiceRestTransport._BaseGetAgent._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.GetAgent", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "GetAgent", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._GetAgent._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = agent.Agent() + pb_resp = agent.Agent.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_agent(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_agent_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = agent.Agent.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.get_agent", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "GetAgent", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetApp(_BaseAgentServiceRestTransport._BaseGetApp, AgentServiceRestStub): + def __hash__(self): + return hash("AgentServiceRestTransport.GetApp") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: agent_service.GetAppRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> app.App: + r"""Call the get app method over HTTP. + + Args: + request (~.agent_service.GetAppRequest): + The request object. Request message for + [AgentService.GetApp][google.cloud.ces.v1beta.AgentService.GetApp]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.app.App: + An app serves as a top-level + container for a group of agents, + including the root agent and its + sub-agents, along with their associated + configurations. These agents work + together to achieve specific goals + within the app's context. + + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseGetApp._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_app(request, metadata) + transcoded_request = ( + _BaseAgentServiceRestTransport._BaseGetApp._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseAgentServiceRestTransport._BaseGetApp._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.GetApp", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "GetApp", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._GetApp._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = app.App() + pb_resp = app.App.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_app(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_app_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = app.App.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.get_app", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "GetApp", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetAppVersion( + _BaseAgentServiceRestTransport._BaseGetAppVersion, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.GetAppVersion") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: agent_service.GetAppVersionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> app_version.AppVersion: + r"""Call the get app version method over HTTP. + + Args: + request (~.agent_service.GetAppVersionRequest): + The request object. Request message for + [AgentService.GetAppVersion][google.cloud.ces.v1beta.AgentService.GetAppVersion]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.app_version.AppVersion: + In Customer Engagement Suite (CES), + an app version is a snapshot of the app + at a specific point in time. It is + immutable and cannot be modified once + created. + + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseGetAppVersion._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_app_version(request, metadata) + transcoded_request = _BaseAgentServiceRestTransport._BaseGetAppVersion._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseAgentServiceRestTransport._BaseGetAppVersion._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.GetAppVersion", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "GetAppVersion", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._GetAppVersion._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = app_version.AppVersion() + pb_resp = app_version.AppVersion.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_app_version(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_app_version_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = app_version.AppVersion.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.get_app_version", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "GetAppVersion", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetChangelog( + _BaseAgentServiceRestTransport._BaseGetChangelog, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.GetChangelog") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: agent_service.GetChangelogRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> changelog.Changelog: + r"""Call the get changelog method over HTTP. + + Args: + request (~.agent_service.GetChangelogRequest): + The request object. Request message for + [AgentService.GetChangelog][google.cloud.ces.v1beta.AgentService.GetChangelog]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.changelog.Changelog: + Changelogs represent a change made to + the app or to an resource within the + app. + + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseGetChangelog._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_changelog(request, metadata) + transcoded_request = _BaseAgentServiceRestTransport._BaseGetChangelog._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = ( + _BaseAgentServiceRestTransport._BaseGetChangelog._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.GetChangelog", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "GetChangelog", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._GetChangelog._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = changelog.Changelog() + pb_resp = changelog.Changelog.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_changelog(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_changelog_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = changelog.Changelog.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.get_changelog", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "GetChangelog", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetConversation( + _BaseAgentServiceRestTransport._BaseGetConversation, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.GetConversation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: agent_service.GetConversationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> conversation.Conversation: + r"""Call the get conversation method over HTTP. + + Args: + request (~.agent_service.GetConversationRequest): + The request object. Request message for + [AgentService.GetConversation][google.cloud.ces.v1beta.AgentService.GetConversation]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.conversation.Conversation: + A conversation represents an + interaction between an end user and the + CES app. + + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseGetConversation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_conversation( + request, metadata + ) + transcoded_request = _BaseAgentServiceRestTransport._BaseGetConversation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseAgentServiceRestTransport._BaseGetConversation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.GetConversation", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "GetConversation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._GetConversation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = conversation.Conversation() + pb_resp = conversation.Conversation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_conversation(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_conversation_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = conversation.Conversation.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.get_conversation", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "GetConversation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetDeployment( + _BaseAgentServiceRestTransport._BaseGetDeployment, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.GetDeployment") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: agent_service.GetDeploymentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> deployment.Deployment: + r"""Call the get deployment method over HTTP. + + Args: + request (~.agent_service.GetDeploymentRequest): + The request object. Request message for + [AgentService.GetDeployment][google.cloud.ces.v1beta.AgentService.GetDeployment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.deployment.Deployment: + A deployment represents an immutable, + queryable version of the app. It is used + to deploy an app version with a specific + channel profile. + + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseGetDeployment._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_deployment(request, metadata) + transcoded_request = _BaseAgentServiceRestTransport._BaseGetDeployment._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseAgentServiceRestTransport._BaseGetDeployment._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.GetDeployment", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "GetDeployment", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._GetDeployment._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = deployment.Deployment() + pb_resp = deployment.Deployment.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_deployment(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_deployment_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = deployment.Deployment.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.get_deployment", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "GetDeployment", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetExample( + _BaseAgentServiceRestTransport._BaseGetExample, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.GetExample") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: agent_service.GetExampleRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> example.Example: + r"""Call the get example method over HTTP. + + Args: + request (~.agent_service.GetExampleRequest): + The request object. Request message for + [AgentService.GetExample][google.cloud.ces.v1beta.AgentService.GetExample]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.example.Example: + An example represents a sample + conversation between the user and the + agent(s). + + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseGetExample._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_example(request, metadata) + transcoded_request = ( + _BaseAgentServiceRestTransport._BaseGetExample._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseAgentServiceRestTransport._BaseGetExample._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.GetExample", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "GetExample", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._GetExample._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = example.Example() + pb_resp = example.Example.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_example(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_example_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = example.Example.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.get_example", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "GetExample", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetGuardrail( + _BaseAgentServiceRestTransport._BaseGetGuardrail, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.GetGuardrail") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: agent_service.GetGuardrailRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> guardrail.Guardrail: + r"""Call the get guardrail method over HTTP. + + Args: + request (~.agent_service.GetGuardrailRequest): + The request object. Request message for + [AgentService.GetGuardrail][google.cloud.ces.v1beta.AgentService.GetGuardrail]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.guardrail.Guardrail: + Guardrail contains a list of checks + and balances to keep the agents safe and + secure. + + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseGetGuardrail._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_guardrail(request, metadata) + transcoded_request = _BaseAgentServiceRestTransport._BaseGetGuardrail._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = ( + _BaseAgentServiceRestTransport._BaseGetGuardrail._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.GetGuardrail", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "GetGuardrail", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._GetGuardrail._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = guardrail.Guardrail() + pb_resp = guardrail.Guardrail.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_guardrail(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_guardrail_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = guardrail.Guardrail.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.get_guardrail", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "GetGuardrail", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetTool(_BaseAgentServiceRestTransport._BaseGetTool, AgentServiceRestStub): + def __hash__(self): + return hash("AgentServiceRestTransport.GetTool") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: agent_service.GetToolRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> tool.Tool: + r"""Call the get tool method over HTTP. + + Args: + request (~.agent_service.GetToolRequest): + The request object. Request message for + [AgentService.GetTool][google.cloud.ces.v1beta.AgentService.GetTool]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.tool.Tool: + A tool represents an action that the + CES agent can take to achieve certain + goals. + + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseGetTool._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_tool(request, metadata) + transcoded_request = ( + _BaseAgentServiceRestTransport._BaseGetTool._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseAgentServiceRestTransport._BaseGetTool._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.GetTool", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "GetTool", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._GetTool._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = tool.Tool() + pb_resp = tool.Tool.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_tool(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_tool_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = tool.Tool.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.get_tool", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "GetTool", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetToolset( + _BaseAgentServiceRestTransport._BaseGetToolset, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.GetToolset") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: agent_service.GetToolsetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> toolset.Toolset: + r"""Call the get toolset method over HTTP. + + Args: + request (~.agent_service.GetToolsetRequest): + The request object. Request message for + [AgentService.GetToolset][google.cloud.ces.v1beta.AgentService.GetToolset]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.toolset.Toolset: + A toolset represents a group of + dynamically managed tools that can be + used by the agent. + + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseGetToolset._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_toolset(request, metadata) + transcoded_request = ( + _BaseAgentServiceRestTransport._BaseGetToolset._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseAgentServiceRestTransport._BaseGetToolset._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.GetToolset", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "GetToolset", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._GetToolset._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = toolset.Toolset() + pb_resp = toolset.Toolset.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_toolset(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_toolset_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = toolset.Toolset.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.get_toolset", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "GetToolset", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ImportApp( + _BaseAgentServiceRestTransport._BaseImportApp, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.ImportApp") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: agent_service.ImportAppRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the import app method over HTTP. + + Args: + request (~.agent_service.ImportAppRequest): + The request object. Request message for + [AgentService.ImportApp][google.cloud.ces.v1beta.AgentService.ImportApp]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseImportApp._get_http_options() + ) + + request, metadata = self._interceptor.pre_import_app(request, metadata) + transcoded_request = ( + _BaseAgentServiceRestTransport._BaseImportApp._get_transcoded_request( + http_options, request + ) + ) + + body = _BaseAgentServiceRestTransport._BaseImportApp._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BaseAgentServiceRestTransport._BaseImportApp._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.ImportApp", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "ImportApp", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._ImportApp._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_import_app(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_import_app_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.import_app", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "ImportApp", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListAgents( + _BaseAgentServiceRestTransport._BaseListAgents, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.ListAgents") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: agent_service.ListAgentsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> agent_service.ListAgentsResponse: + r"""Call the list agents method over HTTP. + + Args: + request (~.agent_service.ListAgentsRequest): + The request object. Request message for + [AgentService.ListAgents][google.cloud.ces.v1beta.AgentService.ListAgents]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.agent_service.ListAgentsResponse: + Response message for + [AgentService.ListAgents][google.cloud.ces.v1beta.AgentService.ListAgents]. + + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseListAgents._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_agents(request, metadata) + transcoded_request = ( + _BaseAgentServiceRestTransport._BaseListAgents._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseAgentServiceRestTransport._BaseListAgents._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.ListAgents", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "ListAgents", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._ListAgents._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = agent_service.ListAgentsResponse() + pb_resp = agent_service.ListAgentsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_agents(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_agents_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = agent_service.ListAgentsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.list_agents", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "ListAgents", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListApps(_BaseAgentServiceRestTransport._BaseListApps, AgentServiceRestStub): + def __hash__(self): + return hash("AgentServiceRestTransport.ListApps") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: agent_service.ListAppsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> agent_service.ListAppsResponse: + r"""Call the list apps method over HTTP. + + Args: + request (~.agent_service.ListAppsRequest): + The request object. Request message for + [AgentService.ListApps][google.cloud.ces.v1beta.AgentService.ListApps]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.agent_service.ListAppsResponse: + Response message for + [AgentService.ListApps][google.cloud.ces.v1beta.AgentService.ListApps]. + + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseListApps._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_apps(request, metadata) + transcoded_request = ( + _BaseAgentServiceRestTransport._BaseListApps._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseAgentServiceRestTransport._BaseListApps._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.ListApps", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "ListApps", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._ListApps._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = agent_service.ListAppsResponse() + pb_resp = agent_service.ListAppsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_apps(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_apps_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = agent_service.ListAppsResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.list_apps", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "ListApps", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListAppVersions( + _BaseAgentServiceRestTransport._BaseListAppVersions, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.ListAppVersions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: agent_service.ListAppVersionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> agent_service.ListAppVersionsResponse: + r"""Call the list app versions method over HTTP. + + Args: + request (~.agent_service.ListAppVersionsRequest): + The request object. Request message for + [AgentService.ListAppVersions][google.cloud.ces.v1beta.AgentService.ListAppVersions]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.agent_service.ListAppVersionsResponse: + Response message for + [AgentService.ListAppVersions][google.cloud.ces.v1beta.AgentService.ListAppVersions]. + + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseListAppVersions._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_app_versions( + request, metadata + ) + transcoded_request = _BaseAgentServiceRestTransport._BaseListAppVersions._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseAgentServiceRestTransport._BaseListAppVersions._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.ListAppVersions", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "ListAppVersions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._ListAppVersions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = agent_service.ListAppVersionsResponse() + pb_resp = agent_service.ListAppVersionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_app_versions(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_app_versions_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = agent_service.ListAppVersionsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.list_app_versions", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "ListAppVersions", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListChangelogs( + _BaseAgentServiceRestTransport._BaseListChangelogs, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.ListChangelogs") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: agent_service.ListChangelogsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> agent_service.ListChangelogsResponse: + r"""Call the list changelogs method over HTTP. + + Args: + request (~.agent_service.ListChangelogsRequest): + The request object. Request message for + [AgentService.ListChangelogs][google.cloud.ces.v1beta.AgentService.ListChangelogs]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.agent_service.ListChangelogsResponse: + Response message for + [AgentService.ListChangelogs][google.cloud.ces.v1beta.AgentService.ListChangelogs]. + + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseListChangelogs._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_changelogs(request, metadata) + transcoded_request = _BaseAgentServiceRestTransport._BaseListChangelogs._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseAgentServiceRestTransport._BaseListChangelogs._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.ListChangelogs", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "ListChangelogs", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._ListChangelogs._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = agent_service.ListChangelogsResponse() + pb_resp = agent_service.ListChangelogsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_changelogs(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_changelogs_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = agent_service.ListChangelogsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.list_changelogs", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "ListChangelogs", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListConversations( + _BaseAgentServiceRestTransport._BaseListConversations, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.ListConversations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: agent_service.ListConversationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> agent_service.ListConversationsResponse: + r"""Call the list conversations method over HTTP. + + Args: + request (~.agent_service.ListConversationsRequest): + The request object. Request message for + [AgentService.ListConversations][google.cloud.ces.v1beta.AgentService.ListConversations]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.agent_service.ListConversationsResponse: + Response message for + [AgentService.ListConversations][google.cloud.ces.v1beta.AgentService.ListConversations]. + + """ + + http_options = _BaseAgentServiceRestTransport._BaseListConversations._get_http_options() + + request, metadata = self._interceptor.pre_list_conversations( + request, metadata + ) + transcoded_request = _BaseAgentServiceRestTransport._BaseListConversations._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseAgentServiceRestTransport._BaseListConversations._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.ListConversations", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "ListConversations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._ListConversations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = agent_service.ListConversationsResponse() + pb_resp = agent_service.ListConversationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_conversations(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_conversations_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = agent_service.ListConversationsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.list_conversations", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "ListConversations", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListDeployments( + _BaseAgentServiceRestTransport._BaseListDeployments, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.ListDeployments") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: agent_service.ListDeploymentsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> agent_service.ListDeploymentsResponse: + r"""Call the list deployments method over HTTP. + + Args: + request (~.agent_service.ListDeploymentsRequest): + The request object. Request message for + [AgentService.ListDeployments][google.cloud.ces.v1beta.AgentService.ListDeployments]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.agent_service.ListDeploymentsResponse: + Response message for + [AgentService.ListDeployments][google.cloud.ces.v1beta.AgentService.ListDeployments]. + + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseListDeployments._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_deployments( + request, metadata + ) + transcoded_request = _BaseAgentServiceRestTransport._BaseListDeployments._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseAgentServiceRestTransport._BaseListDeployments._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.ListDeployments", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "ListDeployments", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._ListDeployments._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = agent_service.ListDeploymentsResponse() + pb_resp = agent_service.ListDeploymentsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_deployments(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_deployments_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = agent_service.ListDeploymentsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.list_deployments", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "ListDeployments", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListExamples( + _BaseAgentServiceRestTransport._BaseListExamples, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.ListExamples") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: agent_service.ListExamplesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> agent_service.ListExamplesResponse: + r"""Call the list examples method over HTTP. + + Args: + request (~.agent_service.ListExamplesRequest): + The request object. Request message for + [AgentService.ListExamples][google.cloud.ces.v1beta.AgentService.ListExamples]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.agent_service.ListExamplesResponse: + Response message for + [AgentService.ListExamples][google.cloud.ces.v1beta.AgentService.ListExamples]. + + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseListExamples._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_examples(request, metadata) + transcoded_request = _BaseAgentServiceRestTransport._BaseListExamples._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = ( + _BaseAgentServiceRestTransport._BaseListExamples._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.ListExamples", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "ListExamples", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._ListExamples._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = agent_service.ListExamplesResponse() + pb_resp = agent_service.ListExamplesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_examples(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_examples_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = agent_service.ListExamplesResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.list_examples", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "ListExamples", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListGuardrails( + _BaseAgentServiceRestTransport._BaseListGuardrails, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.ListGuardrails") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: agent_service.ListGuardrailsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> agent_service.ListGuardrailsResponse: + r"""Call the list guardrails method over HTTP. + + Args: + request (~.agent_service.ListGuardrailsRequest): + The request object. Request message for + [AgentService.ListGuardrails][google.cloud.ces.v1beta.AgentService.ListGuardrails]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.agent_service.ListGuardrailsResponse: + Response message for + [AgentService.ListGuardrails][google.cloud.ces.v1beta.AgentService.ListGuardrails]. + + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseListGuardrails._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_guardrails(request, metadata) + transcoded_request = _BaseAgentServiceRestTransport._BaseListGuardrails._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseAgentServiceRestTransport._BaseListGuardrails._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.ListGuardrails", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "ListGuardrails", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._ListGuardrails._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = agent_service.ListGuardrailsResponse() + pb_resp = agent_service.ListGuardrailsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_guardrails(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_guardrails_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = agent_service.ListGuardrailsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.list_guardrails", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "ListGuardrails", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListTools( + _BaseAgentServiceRestTransport._BaseListTools, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.ListTools") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: agent_service.ListToolsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> agent_service.ListToolsResponse: + r"""Call the list tools method over HTTP. + + Args: + request (~.agent_service.ListToolsRequest): + The request object. Request message for + [AgentService.ListTools][google.cloud.ces.v1beta.AgentService.ListTools]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.agent_service.ListToolsResponse: + Response message for + [AgentService.ListTools][google.cloud.ces.v1beta.AgentService.ListTools]. + + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseListTools._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_tools(request, metadata) + transcoded_request = ( + _BaseAgentServiceRestTransport._BaseListTools._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseAgentServiceRestTransport._BaseListTools._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.ListTools", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "ListTools", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._ListTools._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = agent_service.ListToolsResponse() + pb_resp = agent_service.ListToolsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_tools(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_tools_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = agent_service.ListToolsResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.list_tools", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "ListTools", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListToolsets( + _BaseAgentServiceRestTransport._BaseListToolsets, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.ListToolsets") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: agent_service.ListToolsetsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> agent_service.ListToolsetsResponse: + r"""Call the list toolsets method over HTTP. + + Args: + request (~.agent_service.ListToolsetsRequest): + The request object. Request message for + [AgentService.ListToolsets][google.cloud.ces.v1beta.AgentService.ListToolsets]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.agent_service.ListToolsetsResponse: + Response message for + [AgentService.ListToolsets][google.cloud.ces.v1beta.AgentService.ListToolsets]. + + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseListToolsets._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_toolsets(request, metadata) + transcoded_request = _BaseAgentServiceRestTransport._BaseListToolsets._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = ( + _BaseAgentServiceRestTransport._BaseListToolsets._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.ListToolsets", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "ListToolsets", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._ListToolsets._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = agent_service.ListToolsetsResponse() + pb_resp = agent_service.ListToolsetsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_toolsets(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_toolsets_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = agent_service.ListToolsetsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.list_toolsets", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "ListToolsets", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _RestoreAppVersion( + _BaseAgentServiceRestTransport._BaseRestoreAppVersion, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.RestoreAppVersion") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: agent_service.RestoreAppVersionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the restore app version method over HTTP. + + Args: + request (~.agent_service.RestoreAppVersionRequest): + The request object. Request message for + [AgentService.RestoreAppVersion][google.cloud.ces.v1beta.AgentService.RestoreAppVersion] + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseAgentServiceRestTransport._BaseRestoreAppVersion._get_http_options() + + request, metadata = self._interceptor.pre_restore_app_version( + request, metadata + ) + transcoded_request = _BaseAgentServiceRestTransport._BaseRestoreAppVersion._get_transcoded_request( + http_options, request + ) + + body = _BaseAgentServiceRestTransport._BaseRestoreAppVersion._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseAgentServiceRestTransport._BaseRestoreAppVersion._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.RestoreAppVersion", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "RestoreAppVersion", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._RestoreAppVersion._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_restore_app_version(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_restore_app_version_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.restore_app_version", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "RestoreAppVersion", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateAgent( + _BaseAgentServiceRestTransport._BaseUpdateAgent, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.UpdateAgent") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: agent_service.UpdateAgentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_agent.Agent: + r"""Call the update agent method over HTTP. + + Args: + request (~.agent_service.UpdateAgentRequest): + The request object. Request message for + [AgentService.UpdateAgent][google.cloud.ces.v1beta.AgentService.UpdateAgent]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gcc_agent.Agent: + An agent acts as the fundamental + building block that provides + instructions to the Large Language Model + (LLM) for executing specific tasks. + + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseUpdateAgent._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_agent(request, metadata) + transcoded_request = ( + _BaseAgentServiceRestTransport._BaseUpdateAgent._get_transcoded_request( + http_options, request + ) + ) + + body = ( + _BaseAgentServiceRestTransport._BaseUpdateAgent._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseAgentServiceRestTransport._BaseUpdateAgent._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.UpdateAgent", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "UpdateAgent", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._UpdateAgent._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcc_agent.Agent() + pb_resp = gcc_agent.Agent.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_agent(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_agent_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gcc_agent.Agent.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.update_agent", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "UpdateAgent", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateApp( + _BaseAgentServiceRestTransport._BaseUpdateApp, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.UpdateApp") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: agent_service.UpdateAppRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_app.App: + r"""Call the update app method over HTTP. + + Args: + request (~.agent_service.UpdateAppRequest): + The request object. Request message for + [AgentService.UpdateApp][google.cloud.ces.v1beta.AgentService.UpdateApp]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gcc_app.App: + An app serves as a top-level + container for a group of agents, + including the root agent and its + sub-agents, along with their associated + configurations. These agents work + together to achieve specific goals + within the app's context. + + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseUpdateApp._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_app(request, metadata) + transcoded_request = ( + _BaseAgentServiceRestTransport._BaseUpdateApp._get_transcoded_request( + http_options, request + ) + ) + + body = _BaseAgentServiceRestTransport._BaseUpdateApp._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BaseAgentServiceRestTransport._BaseUpdateApp._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.UpdateApp", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "UpdateApp", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._UpdateApp._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcc_app.App() + pb_resp = gcc_app.App.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_app(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_app_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gcc_app.App.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.update_app", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "UpdateApp", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateDeployment( + _BaseAgentServiceRestTransport._BaseUpdateDeployment, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.UpdateDeployment") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: agent_service.UpdateDeploymentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_deployment.Deployment: + r"""Call the update deployment method over HTTP. + + Args: + request (~.agent_service.UpdateDeploymentRequest): + The request object. Request message for + [AgentService.UpdateDeployment][google.cloud.ces.v1beta.AgentService.UpdateDeployment]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gcc_deployment.Deployment: + A deployment represents an immutable, + queryable version of the app. It is used + to deploy an app version with a specific + channel profile. + + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseUpdateDeployment._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_deployment( + request, metadata + ) + transcoded_request = _BaseAgentServiceRestTransport._BaseUpdateDeployment._get_transcoded_request( + http_options, request + ) + + body = _BaseAgentServiceRestTransport._BaseUpdateDeployment._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseAgentServiceRestTransport._BaseUpdateDeployment._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.UpdateDeployment", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "UpdateDeployment", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._UpdateDeployment._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcc_deployment.Deployment() + pb_resp = gcc_deployment.Deployment.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_deployment(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_deployment_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gcc_deployment.Deployment.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.update_deployment", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "UpdateDeployment", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateExample( + _BaseAgentServiceRestTransport._BaseUpdateExample, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.UpdateExample") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: agent_service.UpdateExampleRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_example.Example: + r"""Call the update example method over HTTP. + + Args: + request (~.agent_service.UpdateExampleRequest): + The request object. Request message for + [AgentService.UpdateExample][google.cloud.ces.v1beta.AgentService.UpdateExample]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gcc_example.Example: + An example represents a sample + conversation between the user and the + agent(s). + + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseUpdateExample._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_example(request, metadata) + transcoded_request = _BaseAgentServiceRestTransport._BaseUpdateExample._get_transcoded_request( + http_options, request + ) + + body = _BaseAgentServiceRestTransport._BaseUpdateExample._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseAgentServiceRestTransport._BaseUpdateExample._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.UpdateExample", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "UpdateExample", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._UpdateExample._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcc_example.Example() + pb_resp = gcc_example.Example.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_example(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_example_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gcc_example.Example.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.update_example", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "UpdateExample", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateGuardrail( + _BaseAgentServiceRestTransport._BaseUpdateGuardrail, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.UpdateGuardrail") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: agent_service.UpdateGuardrailRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_guardrail.Guardrail: + r"""Call the update guardrail method over HTTP. + + Args: + request (~.agent_service.UpdateGuardrailRequest): + The request object. Request message for + [AgentService.UpdateGuardrail][google.cloud.ces.v1beta.AgentService.UpdateGuardrail]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gcc_guardrail.Guardrail: + Guardrail contains a list of checks + and balances to keep the agents safe and + secure. + + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseUpdateGuardrail._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_guardrail( + request, metadata + ) + transcoded_request = _BaseAgentServiceRestTransport._BaseUpdateGuardrail._get_transcoded_request( + http_options, request + ) + + body = _BaseAgentServiceRestTransport._BaseUpdateGuardrail._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseAgentServiceRestTransport._BaseUpdateGuardrail._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.UpdateGuardrail", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "UpdateGuardrail", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._UpdateGuardrail._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcc_guardrail.Guardrail() + pb_resp = gcc_guardrail.Guardrail.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_guardrail(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_guardrail_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gcc_guardrail.Guardrail.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.update_guardrail", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "UpdateGuardrail", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateTool( + _BaseAgentServiceRestTransport._BaseUpdateTool, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.UpdateTool") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: agent_service.UpdateToolRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_tool.Tool: + r"""Call the update tool method over HTTP. + + Args: + request (~.agent_service.UpdateToolRequest): + The request object. Request message for + [AgentService.UpdateTool][google.cloud.ces.v1beta.AgentService.UpdateTool]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gcc_tool.Tool: + A tool represents an action that the + CES agent can take to achieve certain + goals. + + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseUpdateTool._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_tool(request, metadata) + transcoded_request = ( + _BaseAgentServiceRestTransport._BaseUpdateTool._get_transcoded_request( + http_options, request + ) + ) + + body = ( + _BaseAgentServiceRestTransport._BaseUpdateTool._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseAgentServiceRestTransport._BaseUpdateTool._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.UpdateTool", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "UpdateTool", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._UpdateTool._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcc_tool.Tool() + pb_resp = gcc_tool.Tool.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_tool(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_tool_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gcc_tool.Tool.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.update_tool", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "UpdateTool", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateToolset( + _BaseAgentServiceRestTransport._BaseUpdateToolset, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.UpdateToolset") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: agent_service.UpdateToolsetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_toolset.Toolset: + r"""Call the update toolset method over HTTP. + + Args: + request (~.agent_service.UpdateToolsetRequest): + The request object. Request message for + [AgentService.UpdateToolset][google.cloud.ces.v1beta.AgentService.UpdateToolset]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gcc_toolset.Toolset: + A toolset represents a group of + dynamically managed tools that can be + used by the agent. + + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseUpdateToolset._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_toolset(request, metadata) + transcoded_request = _BaseAgentServiceRestTransport._BaseUpdateToolset._get_transcoded_request( + http_options, request + ) + + body = _BaseAgentServiceRestTransport._BaseUpdateToolset._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseAgentServiceRestTransport._BaseUpdateToolset._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.UpdateToolset", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "UpdateToolset", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._UpdateToolset._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcc_toolset.Toolset() + pb_resp = gcc_toolset.Toolset.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_toolset(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_toolset_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gcc_toolset.Toolset.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceClient.update_toolset", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "UpdateToolset", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def batch_delete_conversations( + self, + ) -> Callable[ + [agent_service.BatchDeleteConversationsRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BatchDeleteConversations( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def create_agent( + self, + ) -> Callable[[agent_service.CreateAgentRequest], gcc_agent.Agent]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateAgent(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_app( + self, + ) -> Callable[[agent_service.CreateAppRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateApp(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_app_version( + self, + ) -> Callable[[agent_service.CreateAppVersionRequest], gcc_app_version.AppVersion]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateAppVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_deployment( + self, + ) -> Callable[[agent_service.CreateDeploymentRequest], gcc_deployment.Deployment]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateDeployment(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_example( + self, + ) -> Callable[[agent_service.CreateExampleRequest], gcc_example.Example]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateExample(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_guardrail( + self, + ) -> Callable[[agent_service.CreateGuardrailRequest], gcc_guardrail.Guardrail]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateGuardrail(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_tool(self) -> Callable[[agent_service.CreateToolRequest], gcc_tool.Tool]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateTool(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_toolset( + self, + ) -> Callable[[agent_service.CreateToolsetRequest], gcc_toolset.Toolset]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateToolset(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_agent( + self, + ) -> Callable[[agent_service.DeleteAgentRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteAgent(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_app( + self, + ) -> Callable[[agent_service.DeleteAppRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteApp(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_app_version( + self, + ) -> Callable[[agent_service.DeleteAppVersionRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteAppVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_conversation( + self, + ) -> Callable[[agent_service.DeleteConversationRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteConversation(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_deployment( + self, + ) -> Callable[[agent_service.DeleteDeploymentRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteDeployment(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_example( + self, + ) -> Callable[[agent_service.DeleteExampleRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteExample(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_guardrail( + self, + ) -> Callable[[agent_service.DeleteGuardrailRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteGuardrail(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_tool( + self, + ) -> Callable[[agent_service.DeleteToolRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteTool(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_toolset( + self, + ) -> Callable[[agent_service.DeleteToolsetRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteToolset(self._session, self._host, self._interceptor) # type: ignore + + @property + def export_app( + self, + ) -> Callable[[agent_service.ExportAppRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ExportApp(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_agent(self) -> Callable[[agent_service.GetAgentRequest], agent.Agent]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetAgent(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_app(self) -> Callable[[agent_service.GetAppRequest], app.App]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetApp(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_app_version( + self, + ) -> Callable[[agent_service.GetAppVersionRequest], app_version.AppVersion]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetAppVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_changelog( + self, + ) -> Callable[[agent_service.GetChangelogRequest], changelog.Changelog]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetChangelog(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_conversation( + self, + ) -> Callable[[agent_service.GetConversationRequest], conversation.Conversation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetConversation(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_deployment( + self, + ) -> Callable[[agent_service.GetDeploymentRequest], deployment.Deployment]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetDeployment(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_example( + self, + ) -> Callable[[agent_service.GetExampleRequest], example.Example]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetExample(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_guardrail( + self, + ) -> Callable[[agent_service.GetGuardrailRequest], guardrail.Guardrail]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetGuardrail(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_tool(self) -> Callable[[agent_service.GetToolRequest], tool.Tool]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetTool(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_toolset( + self, + ) -> Callable[[agent_service.GetToolsetRequest], toolset.Toolset]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetToolset(self._session, self._host, self._interceptor) # type: ignore + + @property + def import_app( + self, + ) -> Callable[[agent_service.ImportAppRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ImportApp(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_agents( + self, + ) -> Callable[[agent_service.ListAgentsRequest], agent_service.ListAgentsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListAgents(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_apps( + self, + ) -> Callable[[agent_service.ListAppsRequest], agent_service.ListAppsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListApps(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_app_versions( + self, + ) -> Callable[ + [agent_service.ListAppVersionsRequest], agent_service.ListAppVersionsResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListAppVersions(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_changelogs( + self, + ) -> Callable[ + [agent_service.ListChangelogsRequest], agent_service.ListChangelogsResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListChangelogs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_conversations( + self, + ) -> Callable[ + [agent_service.ListConversationsRequest], + agent_service.ListConversationsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListConversations(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_deployments( + self, + ) -> Callable[ + [agent_service.ListDeploymentsRequest], agent_service.ListDeploymentsResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListDeployments(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_examples( + self, + ) -> Callable[ + [agent_service.ListExamplesRequest], agent_service.ListExamplesResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListExamples(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_guardrails( + self, + ) -> Callable[ + [agent_service.ListGuardrailsRequest], agent_service.ListGuardrailsResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListGuardrails(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_tools( + self, + ) -> Callable[[agent_service.ListToolsRequest], agent_service.ListToolsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListTools(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_toolsets( + self, + ) -> Callable[ + [agent_service.ListToolsetsRequest], agent_service.ListToolsetsResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListToolsets(self._session, self._host, self._interceptor) # type: ignore + + @property + def restore_app_version( + self, + ) -> Callable[[agent_service.RestoreAppVersionRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RestoreAppVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_agent( + self, + ) -> Callable[[agent_service.UpdateAgentRequest], gcc_agent.Agent]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateAgent(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_app(self) -> Callable[[agent_service.UpdateAppRequest], gcc_app.App]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateApp(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_deployment( + self, + ) -> Callable[[agent_service.UpdateDeploymentRequest], gcc_deployment.Deployment]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateDeployment(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_example( + self, + ) -> Callable[[agent_service.UpdateExampleRequest], gcc_example.Example]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateExample(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_guardrail( + self, + ) -> Callable[[agent_service.UpdateGuardrailRequest], gcc_guardrail.Guardrail]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateGuardrail(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_tool(self) -> Callable[[agent_service.UpdateToolRequest], gcc_tool.Tool]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateTool(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_toolset( + self, + ) -> Callable[[agent_service.UpdateToolsetRequest], gcc_toolset.Toolset]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateToolset(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation( + _BaseAgentServiceRestTransport._BaseGetLocation, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.GetLocation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: locations_pb2.GetLocationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseGetLocation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_location(request, metadata) + transcoded_request = ( + _BaseAgentServiceRestTransport._BaseGetLocation._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseAgentServiceRestTransport._BaseGetLocation._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.GetLocation", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "GetLocation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._GetLocation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.Location() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_location(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceAsyncClient.GetLocation", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "GetLocation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations( + _BaseAgentServiceRestTransport._BaseListLocations, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.ListLocations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: locations_pb2.ListLocationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseListLocations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + transcoded_request = _BaseAgentServiceRestTransport._BaseListLocations._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseAgentServiceRestTransport._BaseListLocations._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.ListLocations", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "ListLocations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._ListLocations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_locations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceAsyncClient.ListLocations", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "ListLocations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation( + _BaseAgentServiceRestTransport._BaseCancelOperation, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseCancelOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + transcoded_request = _BaseAgentServiceRestTransport._BaseCancelOperation._get_transcoded_request( + http_options, request + ) + + body = _BaseAgentServiceRestTransport._BaseCancelOperation._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseAgentServiceRestTransport._BaseCancelOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.CancelOperation", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation( + _BaseAgentServiceRestTransport._BaseDeleteOperation, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.DeleteOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseDeleteOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_operation( + request, metadata + ) + transcoded_request = _BaseAgentServiceRestTransport._BaseDeleteOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseAgentServiceRestTransport._BaseDeleteOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.DeleteOperation", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "DeleteOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._DeleteOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation( + _BaseAgentServiceRestTransport._BaseGetOperation, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseGetOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseAgentServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = ( + _BaseAgentServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.GetOperation", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceAsyncClient.GetOperation", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations( + _BaseAgentServiceRestTransport._BaseListOperations, AgentServiceRestStub + ): + def __hash__(self): + return hash("AgentServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options = ( + _BaseAgentServiceRestTransport._BaseListOperations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = _BaseAgentServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseAgentServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.AgentServiceClient.ListOperations", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AgentServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.AgentServiceAsyncClient.ListOperations", + extra={ + "serviceName": "google.cloud.ces.v1beta.AgentService", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("AgentServiceRestTransport",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/rest_base.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/rest_base.py new file mode 100644 index 000000000000..01703522a737 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/agent_service/transports/rest_base.py @@ -0,0 +1,2716 @@ +# -*- coding: utf-8 -*- +# 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. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.ces_v1beta.types import ( + agent, + agent_service, + app, + app_version, + changelog, + conversation, + deployment, + example, + guardrail, + tool, + toolset, +) +from google.cloud.ces_v1beta.types import agent as gcc_agent +from google.cloud.ces_v1beta.types import app as gcc_app +from google.cloud.ces_v1beta.types import app_version as gcc_app_version +from google.cloud.ces_v1beta.types import deployment as gcc_deployment +from google.cloud.ces_v1beta.types import example as gcc_example +from google.cloud.ces_v1beta.types import guardrail as gcc_guardrail +from google.cloud.ces_v1beta.types import tool as gcc_tool +from google.cloud.ces_v1beta.types import toolset as gcc_toolset + +from .base import DEFAULT_CLIENT_INFO, AgentServiceTransport + + +class _BaseAgentServiceRestTransport(AgentServiceTransport): + """Base REST backend transport for AgentService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "ces.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'ces.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseBatchDeleteConversations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*/apps/*}/conversations:batchDelete", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.BatchDeleteConversationsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseBatchDeleteConversations._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateAgent: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*/apps/*}/agents", + "body": "agent", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.CreateAgentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseCreateAgent._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateApp: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*}/apps", + "body": "app", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.CreateAppRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseCreateApp._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateAppVersion: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*/apps/*}/versions", + "body": "app_version", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.CreateAppVersionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseCreateAppVersion._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateDeployment: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*/apps/*}/deployments", + "body": "deployment", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.CreateDeploymentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseCreateDeployment._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateExample: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*/apps/*}/examples", + "body": "example", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.CreateExampleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseCreateExample._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateGuardrail: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*/apps/*}/guardrails", + "body": "guardrail", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.CreateGuardrailRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseCreateGuardrail._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateTool: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*/apps/*}/tools", + "body": "tool", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.CreateToolRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseCreateTool._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateToolset: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*/apps/*}/toolsets", + "body": "toolset", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.CreateToolsetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseCreateToolset._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteAgent: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/apps/*/agents/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.DeleteAgentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseDeleteAgent._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteApp: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/apps/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.DeleteAppRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseDeleteApp._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteAppVersion: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/apps/*/versions/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.DeleteAppVersionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseDeleteAppVersion._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteConversation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/apps/*/conversations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.DeleteConversationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseDeleteConversation._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteDeployment: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/apps/*/deployments/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.DeleteDeploymentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseDeleteDeployment._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteExample: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/apps/*/examples/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.DeleteExampleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseDeleteExample._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteGuardrail: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/apps/*/guardrails/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.DeleteGuardrailRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseDeleteGuardrail._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteTool: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/apps/*/tools/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.DeleteToolRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseDeleteTool._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteToolset: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/apps/*/toolsets/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.DeleteToolsetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseDeleteToolset._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseExportApp: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/apps/*}:exportApp", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.ExportAppRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseExportApp._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetAgent: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/apps/*/agents/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.GetAgentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseGetAgent._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetApp: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/apps/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.GetAppRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseGetApp._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetAppVersion: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/apps/*/versions/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.GetAppVersionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseGetAppVersion._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetChangelog: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/apps/*/changelogs/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.GetChangelogRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseGetChangelog._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetConversation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/apps/*/conversations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.GetConversationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseGetConversation._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetDeployment: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/apps/*/deployments/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.GetDeploymentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseGetDeployment._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetExample: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/apps/*/examples/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.GetExampleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseGetExample._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetGuardrail: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/apps/*/guardrails/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.GetGuardrailRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseGetGuardrail._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetTool: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/apps/*/tools/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.GetToolRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseGetTool._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetToolset: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/apps/*/toolsets/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.GetToolsetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseGetToolset._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseImportApp: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*}/apps:importApp", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.ImportAppRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseImportApp._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListAgents: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*/apps/*}/agents", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.ListAgentsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseListAgents._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListApps: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*}/apps", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.ListAppsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseListApps._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListAppVersions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*/apps/*}/versions", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.ListAppVersionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseListAppVersions._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListChangelogs: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*/apps/*}/changelogs", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.ListChangelogsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseListChangelogs._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListConversations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*/apps/*}/conversations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.ListConversationsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseListConversations._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListDeployments: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*/apps/*}/deployments", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.ListDeploymentsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseListDeployments._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListExamples: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*/apps/*}/examples", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.ListExamplesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseListExamples._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListGuardrails: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*/apps/*}/guardrails", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.ListGuardrailsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseListGuardrails._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListTools: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*/apps/*}/tools", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.ListToolsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseListTools._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListToolsets: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*/apps/*}/toolsets", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.ListToolsetsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseListToolsets._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRestoreAppVersion: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/apps/*/versions/*}:restore", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.RestoreAppVersionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseRestoreAppVersion._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateAgent: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta/{agent.name=projects/*/locations/*/apps/*/agents/*}", + "body": "agent", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.UpdateAgentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseUpdateAgent._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateApp: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta/{app.name=projects/*/locations/*/apps/*}", + "body": "app", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.UpdateAppRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseUpdateApp._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateDeployment: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta/{deployment.name=projects/*/locations/*/apps/*/deployments/*}", + "body": "deployment", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.UpdateDeploymentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseUpdateDeployment._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateExample: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta/{example.name=projects/*/locations/*/apps/*/examples/*}", + "body": "example", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.UpdateExampleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseUpdateExample._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateGuardrail: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta/{guardrail.name=projects/*/locations/*/apps/*/guardrails/*}", + "body": "guardrail", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.UpdateGuardrailRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseUpdateGuardrail._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateTool: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta/{tool.name=projects/*/locations/*/apps/*/tools/*}", + "body": "tool", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.UpdateToolRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseUpdateTool._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateToolset: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta/{toolset.name=projects/*/locations/*/apps/*/toolsets/*}", + "body": "toolset", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = agent_service.UpdateToolsetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAgentServiceRestTransport._BaseUpdateToolset._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetLocation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListLocations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*}/locations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseAgentServiceRestTransport",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/__init__.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/__init__.py new file mode 100644 index 000000000000..9cbde8f5c38c --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# 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 .async_client import EvaluationServiceAsyncClient +from .client import EvaluationServiceClient + +__all__ = ( + "EvaluationServiceClient", + "EvaluationServiceAsyncClient", +) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/async_client.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/async_client.py new file mode 100644 index 000000000000..2262a1dd51db --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/async_client.py @@ -0,0 +1,4557 @@ +# -*- coding: utf-8 -*- +# 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. +# +import logging as std_logging +import re +from collections import OrderedDict +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.ces_v1beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.ces_v1beta.services.evaluation_service import pagers +from google.cloud.ces_v1beta.types import ( + app, + evaluation, + evaluation_service, + golden_run, +) +from google.cloud.ces_v1beta.types import evaluation as gcc_evaluation + +from .client import EvaluationServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, EvaluationServiceTransport +from .transports.grpc_asyncio import EvaluationServiceGrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class EvaluationServiceAsyncClient: + """EvaluationService exposes methods to perform evaluation for + the CES app. + """ + + _client: EvaluationServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = EvaluationServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = EvaluationServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = EvaluationServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = EvaluationServiceClient._DEFAULT_UNIVERSE + + agent_path = staticmethod(EvaluationServiceClient.agent_path) + parse_agent_path = staticmethod(EvaluationServiceClient.parse_agent_path) + app_path = staticmethod(EvaluationServiceClient.app_path) + parse_app_path = staticmethod(EvaluationServiceClient.parse_app_path) + app_version_path = staticmethod(EvaluationServiceClient.app_version_path) + parse_app_version_path = staticmethod( + EvaluationServiceClient.parse_app_version_path + ) + changelog_path = staticmethod(EvaluationServiceClient.changelog_path) + parse_changelog_path = staticmethod(EvaluationServiceClient.parse_changelog_path) + conversation_path = staticmethod(EvaluationServiceClient.conversation_path) + parse_conversation_path = staticmethod( + EvaluationServiceClient.parse_conversation_path + ) + evaluation_path = staticmethod(EvaluationServiceClient.evaluation_path) + parse_evaluation_path = staticmethod(EvaluationServiceClient.parse_evaluation_path) + evaluation_dataset_path = staticmethod( + EvaluationServiceClient.evaluation_dataset_path + ) + parse_evaluation_dataset_path = staticmethod( + EvaluationServiceClient.parse_evaluation_dataset_path + ) + evaluation_expectation_path = staticmethod( + EvaluationServiceClient.evaluation_expectation_path + ) + parse_evaluation_expectation_path = staticmethod( + EvaluationServiceClient.parse_evaluation_expectation_path + ) + evaluation_result_path = staticmethod( + EvaluationServiceClient.evaluation_result_path + ) + parse_evaluation_result_path = staticmethod( + EvaluationServiceClient.parse_evaluation_result_path + ) + evaluation_run_path = staticmethod(EvaluationServiceClient.evaluation_run_path) + parse_evaluation_run_path = staticmethod( + EvaluationServiceClient.parse_evaluation_run_path + ) + guardrail_path = staticmethod(EvaluationServiceClient.guardrail_path) + parse_guardrail_path = staticmethod(EvaluationServiceClient.parse_guardrail_path) + scheduled_evaluation_run_path = staticmethod( + EvaluationServiceClient.scheduled_evaluation_run_path + ) + parse_scheduled_evaluation_run_path = staticmethod( + EvaluationServiceClient.parse_scheduled_evaluation_run_path + ) + tool_path = staticmethod(EvaluationServiceClient.tool_path) + parse_tool_path = staticmethod(EvaluationServiceClient.parse_tool_path) + toolset_path = staticmethod(EvaluationServiceClient.toolset_path) + parse_toolset_path = staticmethod(EvaluationServiceClient.parse_toolset_path) + common_billing_account_path = staticmethod( + EvaluationServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + EvaluationServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(EvaluationServiceClient.common_folder_path) + parse_common_folder_path = staticmethod( + EvaluationServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + EvaluationServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + EvaluationServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod(EvaluationServiceClient.common_project_path) + parse_common_project_path = staticmethod( + EvaluationServiceClient.parse_common_project_path + ) + common_location_path = staticmethod(EvaluationServiceClient.common_location_path) + parse_common_location_path = staticmethod( + EvaluationServiceClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + EvaluationServiceAsyncClient: The constructed client. + """ + sa_info_func = ( + EvaluationServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(EvaluationServiceAsyncClient, info, *args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + EvaluationServiceAsyncClient: The constructed client. + """ + sa_file_func = ( + EvaluationServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(EvaluationServiceAsyncClient, filename, *args, **kwargs) + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return EvaluationServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> EvaluationServiceTransport: + """Returns the transport used by the client instance. + + Returns: + EvaluationServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = EvaluationServiceClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + EvaluationServiceTransport, + Callable[..., EvaluationServiceTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the evaluation service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,EvaluationServiceTransport,Callable[..., EvaluationServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the EvaluationServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = EvaluationServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.ces_v1beta.EvaluationServiceAsyncClient`.", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "credentialsType": None, + }, + ) + + async def run_evaluation( + self, + request: Optional[Union[evaluation.RunEvaluationRequest, dict]] = None, + *, + app: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Runs an evaluation of the app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_run_evaluation(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.RunEvaluationRequest( + app="app_value", + ) + + # Make the request + operation = client.run_evaluation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.RunEvaluationRequest, dict]]): + The request object. Request message for + [EvaluationService.RunEvaluation][google.cloud.ces.v1beta.EvaluationService.RunEvaluation]. + app (:class:`str`): + Required. The app to evaluate. Format: + ``projects/{project}/locations/{location}/apps/{app}`` + + This corresponds to the ``app`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.ces_v1beta.types.RunEvaluationResponse` Response message for + [EvaluationService.RunEvaluation][google.cloud.ces.v1beta.EvaluationService.RunEvaluation]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [app] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation.RunEvaluationRequest): + request = evaluation.RunEvaluationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if app is not None: + request.app = app + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.run_evaluation + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("app", request.app),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + evaluation_service.RunEvaluationResponse, + metadata_type=evaluation_service.RunEvaluationOperationMetadata, + ) + + # Done; return the response. + return response + + async def upload_evaluation_audio( + self, + request: Optional[ + Union[evaluation_service.UploadEvaluationAudioRequest, dict] + ] = None, + *, + app: Optional[str] = None, + audio_content: Optional[bytes] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation_service.UploadEvaluationAudioResponse: + r"""Uploads audio for use in Golden Evaluations. Stores the audio in + the Cloud Storage bucket defined in + 'App.logging_settings.evaluation_audio_recording_config.gcs_bucket' + and returns a transcript. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_upload_evaluation_audio(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.UploadEvaluationAudioRequest( + app="app_value", + audio_content=b'audio_content_blob', + ) + + # Make the request + response = await client.upload_evaluation_audio(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.UploadEvaluationAudioRequest, dict]]): + The request object. Request message for + [EvaluationService.UploadEvaluationAudio][google.cloud.ces.v1beta.EvaluationService.UploadEvaluationAudio]. + app (:class:`str`): + Required. The resource name of the App for which to + upload the evaluation audio. Format: + ``projects/{project}/locations/{location}/apps/{app}`` + + This corresponds to the ``app`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + audio_content (:class:`bytes`): + Required. The raw audio bytes. + The format of the audio must be + single-channel LINEAR16 with a sample + rate of 16kHz (default + InputAudioConfig). + + This corresponds to the ``audio_content`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.UploadEvaluationAudioResponse: + Response message for + [EvaluationService.UploadEvaluationAudio][google.cloud.ces.v1beta.EvaluationService.UploadEvaluationAudio]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [app, audio_content] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.UploadEvaluationAudioRequest): + request = evaluation_service.UploadEvaluationAudioRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if app is not None: + request.app = app + if audio_content is not None: + request.audio_content = audio_content + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.upload_evaluation_audio + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("app", request.app),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_evaluation( + self, + request: Optional[ + Union[evaluation_service.CreateEvaluationRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + evaluation: Optional[gcc_evaluation.Evaluation] = None, + evaluation_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_evaluation.Evaluation: + r"""Creates an evaluation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_create_evaluation(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + evaluation = ces_v1beta.Evaluation() + evaluation.golden.turns.steps.user_input.text = "text_value" + evaluation.display_name = "display_name_value" + + request = ces_v1beta.CreateEvaluationRequest( + parent="parent_value", + evaluation=evaluation, + ) + + # Make the request + response = await client.create_evaluation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.CreateEvaluationRequest, dict]]): + The request object. Request message for + [EvaluationService.CreateEvaluation][google.cloud.ces.v1beta.EvaluationService.CreateEvaluation]. + parent (:class:`str`): + Required. The app to create the evaluation for. Format: + ``projects/{project}/locations/{location}/apps/{app}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + evaluation (:class:`google.cloud.ces_v1beta.types.Evaluation`): + Required. The evaluation to create. + This corresponds to the ``evaluation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + evaluation_id (:class:`str`): + Optional. The ID to use for the + evaluation, which will become the final + component of the evaluation's resource + name. If not provided, a unique ID will + be automatically assigned for the + evaluation. + + This corresponds to the ``evaluation_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Evaluation: + An evaluation represents all of the + information needed to simulate and + evaluate an agent. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, evaluation, evaluation_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.CreateEvaluationRequest): + request = evaluation_service.CreateEvaluationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if evaluation is not None: + request.evaluation = evaluation + if evaluation_id is not None: + request.evaluation_id = evaluation_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_evaluation + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def generate_evaluation( + self, + request: Optional[ + Union[evaluation_service.GenerateEvaluationRequest, dict] + ] = None, + *, + conversation: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a golden evaluation from a conversation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_generate_evaluation(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.GenerateEvaluationRequest( + conversation="conversation_value", + ) + + # Make the request + operation = client.generate_evaluation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.GenerateEvaluationRequest, dict]]): + The request object. Request message for + [EvaluationService.GenerateEvaluation][google.cloud.ces.v1beta.EvaluationService.GenerateEvaluation]. + conversation (:class:`str`): + Required. The conversation to create the golden + evaluation for. Format: + ``projects/{project}/locations/{location}/apps/{app}/conversations/{conversation}`` + + This corresponds to the ``conversation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.ces_v1beta.types.Evaluation` An evaluation represents all of the information needed to simulate and + evaluate an agent. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [conversation] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.GenerateEvaluationRequest): + request = evaluation_service.GenerateEvaluationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if conversation is not None: + request.conversation = conversation + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.generate_evaluation + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("conversation", request.conversation),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + evaluation.Evaluation, + metadata_type=evaluation_service.GenerateEvaluationOperationMetadata, + ) + + # Done; return the response. + return response + + async def import_evaluations( + self, + request: Optional[ + Union[evaluation_service.ImportEvaluationsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Imports evaluations into the app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_import_evaluations(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ImportEvaluationsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.import_evaluations(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.ImportEvaluationsRequest, dict]]): + The request object. Request message for + [EvaluationService.ImportEvaluations][google.cloud.ces.v1beta.EvaluationService.ImportEvaluations]. + parent (:class:`str`): + Required. The app to import the evaluations into. + Format: + ``projects/{project}/locations/{location}/apps/{app}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.ces_v1beta.types.ImportEvaluationsResponse` Response message for + [EvaluationService.ImportEvaluations][google.cloud.ces.v1beta.EvaluationService.ImportEvaluations]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.ImportEvaluationsRequest): + request = evaluation_service.ImportEvaluationsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.import_evaluations + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + evaluation_service.ImportEvaluationsResponse, + metadata_type=evaluation_service.ImportEvaluationsOperationMetadata, + ) + + # Done; return the response. + return response + + async def create_evaluation_dataset( + self, + request: Optional[ + Union[evaluation_service.CreateEvaluationDatasetRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + evaluation_dataset: Optional[evaluation.EvaluationDataset] = None, + evaluation_dataset_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation.EvaluationDataset: + r"""Creates an evaluation dataset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_create_evaluation_dataset(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + evaluation_dataset = ces_v1beta.EvaluationDataset() + evaluation_dataset.display_name = "display_name_value" + + request = ces_v1beta.CreateEvaluationDatasetRequest( + parent="parent_value", + evaluation_dataset=evaluation_dataset, + ) + + # Make the request + response = await client.create_evaluation_dataset(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.CreateEvaluationDatasetRequest, dict]]): + The request object. Request message for + [EvaluationService.CreateEvaluationDataset][google.cloud.ces.v1beta.EvaluationService.CreateEvaluationDataset]. + parent (:class:`str`): + Required. The app to create the evaluation for. Format: + ``projects/{project}/locations/{location}/apps/{app}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + evaluation_dataset (:class:`google.cloud.ces_v1beta.types.EvaluationDataset`): + Required. The evaluation dataset to + create. + + This corresponds to the ``evaluation_dataset`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + evaluation_dataset_id (:class:`str`): + Optional. The ID to use for the + evaluation dataset, which will become + the final component of the evaluation + dataset's resource name. If not + provided, a unique ID will be + automatically assigned for the + evaluation. + + This corresponds to the ``evaluation_dataset_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.EvaluationDataset: + An evaluation dataset represents a + set of evaluations that are grouped + together basaed on shared tags. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, evaluation_dataset, evaluation_dataset_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.CreateEvaluationDatasetRequest): + request = evaluation_service.CreateEvaluationDatasetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if evaluation_dataset is not None: + request.evaluation_dataset = evaluation_dataset + if evaluation_dataset_id is not None: + request.evaluation_dataset_id = evaluation_dataset_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_evaluation_dataset + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_evaluation( + self, + request: Optional[ + Union[evaluation_service.UpdateEvaluationRequest, dict] + ] = None, + *, + evaluation: Optional[gcc_evaluation.Evaluation] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_evaluation.Evaluation: + r"""Updates an evaluation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_update_evaluation(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + evaluation = ces_v1beta.Evaluation() + evaluation.golden.turns.steps.user_input.text = "text_value" + evaluation.display_name = "display_name_value" + + request = ces_v1beta.UpdateEvaluationRequest( + evaluation=evaluation, + ) + + # Make the request + response = await client.update_evaluation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.UpdateEvaluationRequest, dict]]): + The request object. Request message for + [EvaluationService.UpdateEvaluation][google.cloud.ces.v1beta.EvaluationService.UpdateEvaluation]. + evaluation (:class:`google.cloud.ces_v1beta.types.Evaluation`): + Required. The evaluation to update. + This corresponds to the ``evaluation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to + control which fields get updated. If the + mask is not present, all fields will be + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Evaluation: + An evaluation represents all of the + information needed to simulate and + evaluate an agent. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [evaluation, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.UpdateEvaluationRequest): + request = evaluation_service.UpdateEvaluationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if evaluation is not None: + request.evaluation = evaluation + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_evaluation + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("evaluation.name", request.evaluation.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_evaluation_dataset( + self, + request: Optional[ + Union[evaluation_service.UpdateEvaluationDatasetRequest, dict] + ] = None, + *, + evaluation_dataset: Optional[evaluation.EvaluationDataset] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation.EvaluationDataset: + r"""Updates an evaluation dataset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_update_evaluation_dataset(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + evaluation_dataset = ces_v1beta.EvaluationDataset() + evaluation_dataset.display_name = "display_name_value" + + request = ces_v1beta.UpdateEvaluationDatasetRequest( + evaluation_dataset=evaluation_dataset, + ) + + # Make the request + response = await client.update_evaluation_dataset(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.UpdateEvaluationDatasetRequest, dict]]): + The request object. Request message for + [EvaluationService.UpdateEvaluationDataset][google.cloud.ces.v1beta.EvaluationService.UpdateEvaluationDataset]. + evaluation_dataset (:class:`google.cloud.ces_v1beta.types.EvaluationDataset`): + Required. The evaluation dataset to + update. + + This corresponds to the ``evaluation_dataset`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to + control which fields get updated. If the + mask is not present, all fields will be + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.EvaluationDataset: + An evaluation dataset represents a + set of evaluations that are grouped + together basaed on shared tags. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [evaluation_dataset, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.UpdateEvaluationDatasetRequest): + request = evaluation_service.UpdateEvaluationDatasetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if evaluation_dataset is not None: + request.evaluation_dataset = evaluation_dataset + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_evaluation_dataset + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("evaluation_dataset.name", request.evaluation_dataset.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_evaluation( + self, + request: Optional[ + Union[evaluation_service.DeleteEvaluationRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes an evaluation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_delete_evaluation(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteEvaluationRequest( + name="name_value", + ) + + # Make the request + await client.delete_evaluation(request=request) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.DeleteEvaluationRequest, dict]]): + The request object. Request message for + [EvaluationService.DeleteEvaluation][google.cloud.ces.v1beta.EvaluationService.DeleteEvaluation]. + name (:class:`str`): + Required. The resource name of the + evaluation to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.DeleteEvaluationRequest): + request = evaluation_service.DeleteEvaluationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_evaluation + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def delete_evaluation_result( + self, + request: Optional[ + Union[evaluation_service.DeleteEvaluationResultRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes an evaluation result. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_delete_evaluation_result(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteEvaluationResultRequest( + name="name_value", + ) + + # Make the request + await client.delete_evaluation_result(request=request) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.DeleteEvaluationResultRequest, dict]]): + The request object. Request message for + [EvaluationService.DeleteEvaluationResult][google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationResult]. + name (:class:`str`): + Required. The resource name of the + evaluation result to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.DeleteEvaluationResultRequest): + request = evaluation_service.DeleteEvaluationResultRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_evaluation_result + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def delete_evaluation_dataset( + self, + request: Optional[ + Union[evaluation_service.DeleteEvaluationDatasetRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes an evaluation dataset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_delete_evaluation_dataset(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteEvaluationDatasetRequest( + name="name_value", + ) + + # Make the request + await client.delete_evaluation_dataset(request=request) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.DeleteEvaluationDatasetRequest, dict]]): + The request object. Request message for + [EvaluationService.DeleteEvaluationDataset][google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationDataset]. + name (:class:`str`): + Required. The resource name of the + evaluation dataset to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.DeleteEvaluationDatasetRequest): + request = evaluation_service.DeleteEvaluationDatasetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_evaluation_dataset + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def delete_evaluation_run( + self, + request: Optional[ + Union[evaluation_service.DeleteEvaluationRunRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes an evaluation run. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_delete_evaluation_run(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteEvaluationRunRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_evaluation_run(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.DeleteEvaluationRunRequest, dict]]): + The request object. Request message for + [EvaluationService.DeleteEvaluationRun][google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationRun]. + name (:class:`str`): + Required. The resource name of the + evaluation run to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.DeleteEvaluationRunRequest): + request = evaluation_service.DeleteEvaluationRunRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_evaluation_run + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=evaluation_service.DeleteEvaluationRunOperationMetadata, + ) + + # Done; return the response. + return response + + async def get_evaluation( + self, + request: Optional[Union[evaluation_service.GetEvaluationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation.Evaluation: + r"""Gets details of the specified evaluation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_get_evaluation(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.GetEvaluationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_evaluation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.GetEvaluationRequest, dict]]): + The request object. Request message for + [EvaluationService.GetEvaluation][google.cloud.ces.v1beta.EvaluationService.GetEvaluation]. + name (:class:`str`): + Required. The resource name of the + evaluation to retrieve. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Evaluation: + An evaluation represents all of the + information needed to simulate and + evaluate an agent. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.GetEvaluationRequest): + request = evaluation_service.GetEvaluationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_evaluation + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_evaluation_result( + self, + request: Optional[ + Union[evaluation_service.GetEvaluationResultRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation.EvaluationResult: + r"""Gets details of the specified evaluation result. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_get_evaluation_result(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.GetEvaluationResultRequest( + name="name_value", + ) + + # Make the request + response = await client.get_evaluation_result(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.GetEvaluationResultRequest, dict]]): + The request object. Request message for + [EvaluationService.GetEvaluationResult][google.cloud.ces.v1beta.EvaluationService.GetEvaluationResult]. + name (:class:`str`): + Required. The resource name of the + evaluation result to retrieve. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.EvaluationResult: + An evaluation result represents the + output of running an Evaluation. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.GetEvaluationResultRequest): + request = evaluation_service.GetEvaluationResultRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_evaluation_result + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_evaluation_dataset( + self, + request: Optional[ + Union[evaluation_service.GetEvaluationDatasetRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation.EvaluationDataset: + r"""Gets details of the specified evaluation dataset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_get_evaluation_dataset(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.GetEvaluationDatasetRequest( + name="name_value", + ) + + # Make the request + response = await client.get_evaluation_dataset(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.GetEvaluationDatasetRequest, dict]]): + The request object. Request message for + [EvaluationService.GetEvaluationDataset][google.cloud.ces.v1beta.EvaluationService.GetEvaluationDataset]. + name (:class:`str`): + Required. The resource name of the + evaluation dataset to retrieve. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.EvaluationDataset: + An evaluation dataset represents a + set of evaluations that are grouped + together basaed on shared tags. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.GetEvaluationDatasetRequest): + request = evaluation_service.GetEvaluationDatasetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_evaluation_dataset + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_evaluation_run( + self, + request: Optional[ + Union[evaluation_service.GetEvaluationRunRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation.EvaluationRun: + r"""Gets details of the specified evaluation run. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_get_evaluation_run(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.GetEvaluationRunRequest( + name="name_value", + ) + + # Make the request + response = await client.get_evaluation_run(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.GetEvaluationRunRequest, dict]]): + The request object. Request message for + [EvaluationService.GetEvaluationRun][google.cloud.ces.v1beta.EvaluationService.GetEvaluationRun]. + name (:class:`str`): + Required. The resource name of the + evaluation run to retrieve. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.EvaluationRun: + An evaluation run represents an all + the evaluation results from an + evaluation execution. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.GetEvaluationRunRequest): + request = evaluation_service.GetEvaluationRunRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_evaluation_run + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_evaluations( + self, + request: Optional[ + Union[evaluation_service.ListEvaluationsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListEvaluationsAsyncPager: + r"""Lists all evaluations in the given app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_list_evaluations(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ListEvaluationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_evaluations(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.ListEvaluationsRequest, dict]]): + The request object. Request message for + [EvaluationService.ListEvaluations][google.cloud.ces.v1beta.EvaluationService.ListEvaluations]. + parent (:class:`str`): + Required. The resource name of the + app to list evaluations from. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.services.evaluation_service.pagers.ListEvaluationsAsyncPager: + Response message for + [EvaluationService.ListEvaluations][google.cloud.ces.v1beta.EvaluationService.ListEvaluations]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.ListEvaluationsRequest): + request = evaluation_service.ListEvaluationsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_evaluations + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListEvaluationsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_evaluation_results( + self, + request: Optional[ + Union[evaluation_service.ListEvaluationResultsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListEvaluationResultsAsyncPager: + r"""Lists all evaluation results for a given evaluation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_list_evaluation_results(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ListEvaluationResultsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_evaluation_results(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.ListEvaluationResultsRequest, dict]]): + The request object. Request message for + [EvaluationService.ListEvaluationResults][google.cloud.ces.v1beta.EvaluationService.ListEvaluationResults]. + parent (:class:`str`): + Required. The resource name of the evaluation to list + evaluation results from. To filter by evaluation run, + use ``-`` as the evaluation ID and specify the + evaluation run ID in the filter. For example: + ``projects/{project}/locations/{location}/apps/{app}/evaluations/-`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.services.evaluation_service.pagers.ListEvaluationResultsAsyncPager: + Response message for + [EvaluationService.ListEvaluationResults][google.cloud.ces.v1beta.EvaluationService.ListEvaluationResults]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.ListEvaluationResultsRequest): + request = evaluation_service.ListEvaluationResultsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_evaluation_results + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListEvaluationResultsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_evaluation_datasets( + self, + request: Optional[ + Union[evaluation_service.ListEvaluationDatasetsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListEvaluationDatasetsAsyncPager: + r"""Lists all evaluation datasets in the given app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_list_evaluation_datasets(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ListEvaluationDatasetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_evaluation_datasets(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.ListEvaluationDatasetsRequest, dict]]): + The request object. Request message for + [EvaluationService.ListEvaluationDatasets][google.cloud.ces.v1beta.EvaluationService.ListEvaluationDatasets]. + parent (:class:`str`): + Required. The resource name of the + app to list evaluation datasets from. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.services.evaluation_service.pagers.ListEvaluationDatasetsAsyncPager: + Response message for + [EvaluationService.ListEvaluationDatasets][google.cloud.ces.v1beta.EvaluationService.ListEvaluationDatasets]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.ListEvaluationDatasetsRequest): + request = evaluation_service.ListEvaluationDatasetsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_evaluation_datasets + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListEvaluationDatasetsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_evaluation_runs( + self, + request: Optional[ + Union[evaluation_service.ListEvaluationRunsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListEvaluationRunsAsyncPager: + r"""Lists all evaluation runs in the given app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_list_evaluation_runs(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ListEvaluationRunsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_evaluation_runs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.ListEvaluationRunsRequest, dict]]): + The request object. Request message for + [EvaluationService.ListEvaluationRuns][google.cloud.ces.v1beta.EvaluationService.ListEvaluationRuns]. + parent (:class:`str`): + Required. The resource name of the + app to list evaluation runs from. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.services.evaluation_service.pagers.ListEvaluationRunsAsyncPager: + Response message for + [EvaluationService.ListEvaluationRuns][google.cloud.ces.v1beta.EvaluationService.ListEvaluationRuns]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.ListEvaluationRunsRequest): + request = evaluation_service.ListEvaluationRunsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_evaluation_runs + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListEvaluationRunsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_evaluation_expectations( + self, + request: Optional[ + Union[evaluation_service.ListEvaluationExpectationsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListEvaluationExpectationsAsyncPager: + r"""Lists all evaluation expectations in the given app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_list_evaluation_expectations(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ListEvaluationExpectationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_evaluation_expectations(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.ListEvaluationExpectationsRequest, dict]]): + The request object. Request message for + [EvaluationService.ListEvaluationExpectations][google.cloud.ces.v1beta.EvaluationService.ListEvaluationExpectations]. + parent (:class:`str`): + Required. The resource name of the + app to list evaluation expectations + from. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.services.evaluation_service.pagers.ListEvaluationExpectationsAsyncPager: + Response message for + [EvaluationService.ListEvaluationExpectations][google.cloud.ces.v1beta.EvaluationService.ListEvaluationExpectations]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, evaluation_service.ListEvaluationExpectationsRequest + ): + request = evaluation_service.ListEvaluationExpectationsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_evaluation_expectations + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListEvaluationExpectationsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_evaluation_expectation( + self, + request: Optional[ + Union[evaluation_service.GetEvaluationExpectationRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation.EvaluationExpectation: + r"""Gets details of the specified evaluation expectation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_get_evaluation_expectation(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.GetEvaluationExpectationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_evaluation_expectation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.GetEvaluationExpectationRequest, dict]]): + The request object. Request message for + [EvaluationService.GetEvaluationExpectation][google.cloud.ces.v1beta.EvaluationService.GetEvaluationExpectation]. + name (:class:`str`): + Required. The resource name of the + evaluation expectation to retrieve. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.EvaluationExpectation: + An evaluation expectation represents + a specific criteria to evaluate against. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.GetEvaluationExpectationRequest): + request = evaluation_service.GetEvaluationExpectationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_evaluation_expectation + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_evaluation_expectation( + self, + request: Optional[ + Union[evaluation_service.CreateEvaluationExpectationRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + evaluation_expectation: Optional[evaluation.EvaluationExpectation] = None, + evaluation_expectation_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation.EvaluationExpectation: + r"""Creates an evaluation expectation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_create_evaluation_expectation(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + evaluation_expectation = ces_v1beta.EvaluationExpectation() + evaluation_expectation.llm_criteria.prompt = "prompt_value" + evaluation_expectation.display_name = "display_name_value" + + request = ces_v1beta.CreateEvaluationExpectationRequest( + parent="parent_value", + evaluation_expectation=evaluation_expectation, + ) + + # Make the request + response = await client.create_evaluation_expectation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.CreateEvaluationExpectationRequest, dict]]): + The request object. Request message for + [EvaluationService.CreateEvaluationExpectation][google.cloud.ces.v1beta.EvaluationService.CreateEvaluationExpectation]. + parent (:class:`str`): + Required. The app to create the evaluation expectation + for. Format: + ``projects/{project}/locations/{location}/apps/{app}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + evaluation_expectation (:class:`google.cloud.ces_v1beta.types.EvaluationExpectation`): + Required. The evaluation expectation + to create. + + This corresponds to the ``evaluation_expectation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + evaluation_expectation_id (:class:`str`): + Optional. The ID to use for the + evaluation expectation, which will + become the final component of the + evaluation expectation's resource name. + If not provided, a unique ID will be + automatically assigned for the + evaluation expectation. + + This corresponds to the ``evaluation_expectation_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.EvaluationExpectation: + An evaluation expectation represents + a specific criteria to evaluate against. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, evaluation_expectation, evaluation_expectation_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, evaluation_service.CreateEvaluationExpectationRequest + ): + request = evaluation_service.CreateEvaluationExpectationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if evaluation_expectation is not None: + request.evaluation_expectation = evaluation_expectation + if evaluation_expectation_id is not None: + request.evaluation_expectation_id = evaluation_expectation_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_evaluation_expectation + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_evaluation_expectation( + self, + request: Optional[ + Union[evaluation_service.UpdateEvaluationExpectationRequest, dict] + ] = None, + *, + evaluation_expectation: Optional[evaluation.EvaluationExpectation] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation.EvaluationExpectation: + r"""Updates an evaluation expectation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_update_evaluation_expectation(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + evaluation_expectation = ces_v1beta.EvaluationExpectation() + evaluation_expectation.llm_criteria.prompt = "prompt_value" + evaluation_expectation.display_name = "display_name_value" + + request = ces_v1beta.UpdateEvaluationExpectationRequest( + evaluation_expectation=evaluation_expectation, + ) + + # Make the request + response = await client.update_evaluation_expectation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.UpdateEvaluationExpectationRequest, dict]]): + The request object. Request message for + [EvaluationService.UpdateEvaluationExpectation][google.cloud.ces.v1beta.EvaluationService.UpdateEvaluationExpectation]. + evaluation_expectation (:class:`google.cloud.ces_v1beta.types.EvaluationExpectation`): + Required. The evaluation expectation + to update. + + This corresponds to the ``evaluation_expectation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to + control which fields get updated. If the + mask is not present, all fields will be + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.EvaluationExpectation: + An evaluation expectation represents + a specific criteria to evaluate against. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [evaluation_expectation, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, evaluation_service.UpdateEvaluationExpectationRequest + ): + request = evaluation_service.UpdateEvaluationExpectationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if evaluation_expectation is not None: + request.evaluation_expectation = evaluation_expectation + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_evaluation_expectation + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("evaluation_expectation.name", request.evaluation_expectation.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_evaluation_expectation( + self, + request: Optional[ + Union[evaluation_service.DeleteEvaluationExpectationRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes an evaluation expectation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_delete_evaluation_expectation(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteEvaluationExpectationRequest( + name="name_value", + ) + + # Make the request + await client.delete_evaluation_expectation(request=request) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.DeleteEvaluationExpectationRequest, dict]]): + The request object. Request message for + [EvaluationService.DeleteEvaluationExpectation][google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationExpectation]. + name (:class:`str`): + Required. The resource name of the + evaluation expectation to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, evaluation_service.DeleteEvaluationExpectationRequest + ): + request = evaluation_service.DeleteEvaluationExpectationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_evaluation_expectation + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def create_scheduled_evaluation_run( + self, + request: Optional[ + Union[evaluation_service.CreateScheduledEvaluationRunRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + scheduled_evaluation_run: Optional[evaluation.ScheduledEvaluationRun] = None, + scheduled_evaluation_run_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation.ScheduledEvaluationRun: + r"""Creates a scheduled evaluation run. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_create_scheduled_evaluation_run(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + scheduled_evaluation_run = ces_v1beta.ScheduledEvaluationRun() + scheduled_evaluation_run.display_name = "display_name_value" + scheduled_evaluation_run.request.app = "app_value" + scheduled_evaluation_run.scheduling_config.frequency = "BIWEEKLY" + + request = ces_v1beta.CreateScheduledEvaluationRunRequest( + parent="parent_value", + scheduled_evaluation_run=scheduled_evaluation_run, + ) + + # Make the request + response = await client.create_scheduled_evaluation_run(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.CreateScheduledEvaluationRunRequest, dict]]): + The request object. Request message for + [EvaluationService.CreateScheduledEvaluationRun][google.cloud.ces.v1beta.EvaluationService.CreateScheduledEvaluationRun]. + parent (:class:`str`): + Required. The app to create the scheduled evaluation run + for. Format: + ``projects/{project}/locations/{location}/apps/{app}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + scheduled_evaluation_run (:class:`google.cloud.ces_v1beta.types.ScheduledEvaluationRun`): + Required. The scheduled evaluation + run to create. + + This corresponds to the ``scheduled_evaluation_run`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + scheduled_evaluation_run_id (:class:`str`): + Optional. The ID to use for the + scheduled evaluation run, which will + become the final component of the + scheduled evaluation run's resource + name. If not provided, a unique ID will + be automatically assigned. + + This corresponds to the ``scheduled_evaluation_run_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.ScheduledEvaluationRun: + Represents a scheduled evaluation run + configuration. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [ + parent, + scheduled_evaluation_run, + scheduled_evaluation_run_id, + ] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, evaluation_service.CreateScheduledEvaluationRunRequest + ): + request = evaluation_service.CreateScheduledEvaluationRunRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if scheduled_evaluation_run is not None: + request.scheduled_evaluation_run = scheduled_evaluation_run + if scheduled_evaluation_run_id is not None: + request.scheduled_evaluation_run_id = scheduled_evaluation_run_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_scheduled_evaluation_run + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_scheduled_evaluation_run( + self, + request: Optional[ + Union[evaluation_service.GetScheduledEvaluationRunRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation.ScheduledEvaluationRun: + r"""Gets details of the specified scheduled evaluation + run. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_get_scheduled_evaluation_run(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.GetScheduledEvaluationRunRequest( + name="name_value", + ) + + # Make the request + response = await client.get_scheduled_evaluation_run(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.GetScheduledEvaluationRunRequest, dict]]): + The request object. Request message for + [EvaluationService.GetScheduledEvaluationRun][google.cloud.ces.v1beta.EvaluationService.GetScheduledEvaluationRun]. + name (:class:`str`): + Required. The resource name of the + scheduled evaluation run to retrieve. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.ScheduledEvaluationRun: + Represents a scheduled evaluation run + configuration. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.GetScheduledEvaluationRunRequest): + request = evaluation_service.GetScheduledEvaluationRunRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_scheduled_evaluation_run + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_scheduled_evaluation_runs( + self, + request: Optional[ + Union[evaluation_service.ListScheduledEvaluationRunsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListScheduledEvaluationRunsAsyncPager: + r"""Lists all scheduled evaluation runs in the given app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_list_scheduled_evaluation_runs(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ListScheduledEvaluationRunsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_scheduled_evaluation_runs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.ListScheduledEvaluationRunsRequest, dict]]): + The request object. Request message for + [EvaluationService.ListScheduledEvaluationRuns][google.cloud.ces.v1beta.EvaluationService.ListScheduledEvaluationRuns]. + parent (:class:`str`): + Required. The resource name of the + app to list scheduled evaluation runs + from. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.services.evaluation_service.pagers.ListScheduledEvaluationRunsAsyncPager: + Response message for + [EvaluationService.ListScheduledEvaluationRuns][google.cloud.ces.v1beta.EvaluationService.ListScheduledEvaluationRuns]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, evaluation_service.ListScheduledEvaluationRunsRequest + ): + request = evaluation_service.ListScheduledEvaluationRunsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_scheduled_evaluation_runs + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListScheduledEvaluationRunsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_scheduled_evaluation_run( + self, + request: Optional[ + Union[evaluation_service.UpdateScheduledEvaluationRunRequest, dict] + ] = None, + *, + scheduled_evaluation_run: Optional[evaluation.ScheduledEvaluationRun] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation.ScheduledEvaluationRun: + r"""Updates a scheduled evaluation run. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_update_scheduled_evaluation_run(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + scheduled_evaluation_run = ces_v1beta.ScheduledEvaluationRun() + scheduled_evaluation_run.display_name = "display_name_value" + scheduled_evaluation_run.request.app = "app_value" + scheduled_evaluation_run.scheduling_config.frequency = "BIWEEKLY" + + request = ces_v1beta.UpdateScheduledEvaluationRunRequest( + scheduled_evaluation_run=scheduled_evaluation_run, + ) + + # Make the request + response = await client.update_scheduled_evaluation_run(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.UpdateScheduledEvaluationRunRequest, dict]]): + The request object. Request message for + [EvaluationService.UpdateScheduledEvaluationRun][google.cloud.ces.v1beta.EvaluationService.UpdateScheduledEvaluationRun]. + scheduled_evaluation_run (:class:`google.cloud.ces_v1beta.types.ScheduledEvaluationRun`): + Required. The scheduled evaluation + run to update. + + This corresponds to the ``scheduled_evaluation_run`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to + control which fields get updated. If the + mask is not present, all fields will be + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.ScheduledEvaluationRun: + Represents a scheduled evaluation run + configuration. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [scheduled_evaluation_run, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, evaluation_service.UpdateScheduledEvaluationRunRequest + ): + request = evaluation_service.UpdateScheduledEvaluationRunRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if scheduled_evaluation_run is not None: + request.scheduled_evaluation_run = scheduled_evaluation_run + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_scheduled_evaluation_run + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ( + "scheduled_evaluation_run.name", + request.scheduled_evaluation_run.name, + ), + ) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_scheduled_evaluation_run( + self, + request: Optional[ + Union[evaluation_service.DeleteScheduledEvaluationRunRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a scheduled evaluation run. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_delete_scheduled_evaluation_run(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteScheduledEvaluationRunRequest( + name="name_value", + ) + + # Make the request + await client.delete_scheduled_evaluation_run(request=request) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.DeleteScheduledEvaluationRunRequest, dict]]): + The request object. Request message for + [EvaluationService.DeleteScheduledEvaluationRun][google.cloud.ces.v1beta.EvaluationService.DeleteScheduledEvaluationRun]. + name (:class:`str`): + Required. The resource name of the + scheduled evaluation run to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, evaluation_service.DeleteScheduledEvaluationRunRequest + ): + request = evaluation_service.DeleteScheduledEvaluationRunRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_scheduled_evaluation_run + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def test_persona_voice( + self, + request: Optional[ + Union[evaluation_service.TestPersonaVoiceRequest, dict] + ] = None, + *, + app: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation_service.TestPersonaVoiceResponse: + r"""Tests the voice of a persona. Also accepts a default + persona. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_test_persona_voice(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.TestPersonaVoiceRequest( + app="app_value", + persona_id="persona_id_value", + text="text_value", + ) + + # Make the request + response = await client.test_persona_voice(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.TestPersonaVoiceRequest, dict]]): + The request object. Request message for + [EvaluationService.TestPersonaVoice][google.cloud.ces.v1beta.EvaluationService.TestPersonaVoice]. + app (:class:`str`): + Required. the resource name of the app to test the + persona voice for. Format: + ``projects/{project}/locations/{location}/apps/{app}`` + + This corresponds to the ``app`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.TestPersonaVoiceResponse: + Response message for + [EvaluationService.TestPersonaVoice][google.cloud.ces.v1beta.EvaluationService.TestPersonaVoice]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [app] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.TestPersonaVoiceRequest): + request = evaluation_service.TestPersonaVoiceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if app is not None: + request.app = app + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.test_persona_voice + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("app", request.app),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.delete_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "EvaluationServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("EvaluationServiceAsyncClient",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/client.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/client.py new file mode 100644 index 000000000000..642b52c06483 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/client.py @@ -0,0 +1,5211 @@ +# -*- coding: utf-8 -*- +# 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. +# +import json +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.ces_v1beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +import google.api_core.operation as operation # type: ignore +import google.api_core.operation_async as operation_async # type: ignore +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.ces_v1beta.services.evaluation_service import pagers +from google.cloud.ces_v1beta.types import ( + app, + evaluation, + evaluation_service, + golden_run, +) +from google.cloud.ces_v1beta.types import evaluation as gcc_evaluation + +from .transports.base import DEFAULT_CLIENT_INFO, EvaluationServiceTransport +from .transports.grpc import EvaluationServiceGrpcTransport +from .transports.grpc_asyncio import EvaluationServiceGrpcAsyncIOTransport +from .transports.rest import EvaluationServiceRestTransport + + +class EvaluationServiceClientMeta(type): + """Metaclass for the EvaluationService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[EvaluationServiceTransport]] + _transport_registry["grpc"] = EvaluationServiceGrpcTransport + _transport_registry["grpc_asyncio"] = EvaluationServiceGrpcAsyncIOTransport + _transport_registry["rest"] = EvaluationServiceRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[EvaluationServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class EvaluationServiceClient(metaclass=EvaluationServiceClientMeta): + """EvaluationService exposes methods to perform evaluation for + the CES app. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "ces.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "ces.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + EvaluationServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + EvaluationServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> EvaluationServiceTransport: + """Returns the transport used by the client instance. + + Returns: + EvaluationServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def agent_path( + project: str, + location: str, + app: str, + agent: str, + ) -> str: + """Returns a fully-qualified agent string.""" + return ( + "projects/{project}/locations/{location}/apps/{app}/agents/{agent}".format( + project=project, + location=location, + app=app, + agent=agent, + ) + ) + + @staticmethod + def parse_agent_path(path: str) -> Dict[str, str]: + """Parses a agent path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/apps/(?P.+?)/agents/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def app_path( + project: str, + location: str, + app: str, + ) -> str: + """Returns a fully-qualified app string.""" + return "projects/{project}/locations/{location}/apps/{app}".format( + project=project, + location=location, + app=app, + ) + + @staticmethod + def parse_app_path(path: str) -> Dict[str, str]: + """Parses a app path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/apps/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def app_version_path( + project: str, + location: str, + app: str, + version: str, + ) -> str: + """Returns a fully-qualified app_version string.""" + return "projects/{project}/locations/{location}/apps/{app}/versions/{version}".format( + project=project, + location=location, + app=app, + version=version, + ) + + @staticmethod + def parse_app_version_path(path: str) -> Dict[str, str]: + """Parses a app_version path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/apps/(?P.+?)/versions/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def changelog_path( + project: str, + location: str, + app: str, + changelog: str, + ) -> str: + """Returns a fully-qualified changelog string.""" + return "projects/{project}/locations/{location}/apps/{app}/changelogs/{changelog}".format( + project=project, + location=location, + app=app, + changelog=changelog, + ) + + @staticmethod + def parse_changelog_path(path: str) -> Dict[str, str]: + """Parses a changelog path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/apps/(?P.+?)/changelogs/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def conversation_path( + project: str, + location: str, + app: str, + conversation: str, + ) -> str: + """Returns a fully-qualified conversation string.""" + return "projects/{project}/locations/{location}/apps/{app}/conversations/{conversation}".format( + project=project, + location=location, + app=app, + conversation=conversation, + ) + + @staticmethod + def parse_conversation_path(path: str) -> Dict[str, str]: + """Parses a conversation path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/apps/(?P.+?)/conversations/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def evaluation_path( + project: str, + location: str, + app: str, + evaluation: str, + ) -> str: + """Returns a fully-qualified evaluation string.""" + return "projects/{project}/locations/{location}/apps/{app}/evaluations/{evaluation}".format( + project=project, + location=location, + app=app, + evaluation=evaluation, + ) + + @staticmethod + def parse_evaluation_path(path: str) -> Dict[str, str]: + """Parses a evaluation path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/apps/(?P.+?)/evaluations/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def evaluation_dataset_path( + project: str, + location: str, + app: str, + evaluation_dataset: str, + ) -> str: + """Returns a fully-qualified evaluation_dataset string.""" + return "projects/{project}/locations/{location}/apps/{app}/evaluationDatasets/{evaluation_dataset}".format( + project=project, + location=location, + app=app, + evaluation_dataset=evaluation_dataset, + ) + + @staticmethod + def parse_evaluation_dataset_path(path: str) -> Dict[str, str]: + """Parses a evaluation_dataset path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/apps/(?P.+?)/evaluationDatasets/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def evaluation_expectation_path( + project: str, + location: str, + app: str, + evaluation_expectation: str, + ) -> str: + """Returns a fully-qualified evaluation_expectation string.""" + return "projects/{project}/locations/{location}/apps/{app}/evaluationExpectations/{evaluation_expectation}".format( + project=project, + location=location, + app=app, + evaluation_expectation=evaluation_expectation, + ) + + @staticmethod + def parse_evaluation_expectation_path(path: str) -> Dict[str, str]: + """Parses a evaluation_expectation path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/apps/(?P.+?)/evaluationExpectations/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def evaluation_result_path( + project: str, + location: str, + app: str, + evaluation: str, + evaluation_result: str, + ) -> str: + """Returns a fully-qualified evaluation_result string.""" + return "projects/{project}/locations/{location}/apps/{app}/evaluations/{evaluation}/results/{evaluation_result}".format( + project=project, + location=location, + app=app, + evaluation=evaluation, + evaluation_result=evaluation_result, + ) + + @staticmethod + def parse_evaluation_result_path(path: str) -> Dict[str, str]: + """Parses a evaluation_result path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/apps/(?P.+?)/evaluations/(?P.+?)/results/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def evaluation_run_path( + project: str, + location: str, + app: str, + evaluation_run: str, + ) -> str: + """Returns a fully-qualified evaluation_run string.""" + return "projects/{project}/locations/{location}/apps/{app}/evaluationRuns/{evaluation_run}".format( + project=project, + location=location, + app=app, + evaluation_run=evaluation_run, + ) + + @staticmethod + def parse_evaluation_run_path(path: str) -> Dict[str, str]: + """Parses a evaluation_run path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/apps/(?P.+?)/evaluationRuns/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def guardrail_path( + project: str, + location: str, + app: str, + guardrail: str, + ) -> str: + """Returns a fully-qualified guardrail string.""" + return "projects/{project}/locations/{location}/apps/{app}/guardrails/{guardrail}".format( + project=project, + location=location, + app=app, + guardrail=guardrail, + ) + + @staticmethod + def parse_guardrail_path(path: str) -> Dict[str, str]: + """Parses a guardrail path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/apps/(?P.+?)/guardrails/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def scheduled_evaluation_run_path( + project: str, + location: str, + app: str, + scheduled_evaluation_run: str, + ) -> str: + """Returns a fully-qualified scheduled_evaluation_run string.""" + return "projects/{project}/locations/{location}/apps/{app}/scheduledEvaluationRuns/{scheduled_evaluation_run}".format( + project=project, + location=location, + app=app, + scheduled_evaluation_run=scheduled_evaluation_run, + ) + + @staticmethod + def parse_scheduled_evaluation_run_path(path: str) -> Dict[str, str]: + """Parses a scheduled_evaluation_run path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/apps/(?P.+?)/scheduledEvaluationRuns/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def tool_path( + project: str, + location: str, + app: str, + tool: str, + ) -> str: + """Returns a fully-qualified tool string.""" + return "projects/{project}/locations/{location}/apps/{app}/tools/{tool}".format( + project=project, + location=location, + app=app, + tool=tool, + ) + + @staticmethod + def parse_tool_path(path: str) -> Dict[str, str]: + """Parses a tool path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/apps/(?P.+?)/tools/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def toolset_path( + project: str, + location: str, + app: str, + toolset: str, + ) -> str: + """Returns a fully-qualified toolset string.""" + return "projects/{project}/locations/{location}/apps/{app}/toolsets/{toolset}".format( + project=project, + location=location, + app=app, + toolset=toolset, + ) + + @staticmethod + def parse_toolset_path(path: str) -> Dict[str, str]: + """Parses a toolset path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/apps/(?P.+?)/toolsets/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = EvaluationServiceClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = EvaluationServiceClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = EvaluationServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = EvaluationServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = EvaluationServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = EvaluationServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + EvaluationServiceTransport, + Callable[..., EvaluationServiceTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the evaluation service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,EvaluationServiceTransport,Callable[..., EvaluationServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the EvaluationServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + EvaluationServiceClient._read_environment_variables() + ) + self._client_cert_source = EvaluationServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = EvaluationServiceClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, EvaluationServiceTransport) + if transport_provided: + # transport is a EvaluationServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(EvaluationServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or EvaluationServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[EvaluationServiceTransport], + Callable[..., EvaluationServiceTransport], + ] = ( + EvaluationServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., EvaluationServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.ces_v1beta.EvaluationServiceClient`.", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "credentialsType": None, + }, + ) + + def run_evaluation( + self, + request: Optional[Union[evaluation.RunEvaluationRequest, dict]] = None, + *, + app: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Runs an evaluation of the app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_run_evaluation(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.RunEvaluationRequest( + app="app_value", + ) + + # Make the request + operation = client.run_evaluation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.RunEvaluationRequest, dict]): + The request object. Request message for + [EvaluationService.RunEvaluation][google.cloud.ces.v1beta.EvaluationService.RunEvaluation]. + app (str): + Required. The app to evaluate. Format: + ``projects/{project}/locations/{location}/apps/{app}`` + + This corresponds to the ``app`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.ces_v1beta.types.RunEvaluationResponse` Response message for + [EvaluationService.RunEvaluation][google.cloud.ces.v1beta.EvaluationService.RunEvaluation]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [app] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation.RunEvaluationRequest): + request = evaluation.RunEvaluationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if app is not None: + request.app = app + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.run_evaluation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("app", request.app),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + evaluation_service.RunEvaluationResponse, + metadata_type=evaluation_service.RunEvaluationOperationMetadata, + ) + + # Done; return the response. + return response + + def upload_evaluation_audio( + self, + request: Optional[ + Union[evaluation_service.UploadEvaluationAudioRequest, dict] + ] = None, + *, + app: Optional[str] = None, + audio_content: Optional[bytes] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation_service.UploadEvaluationAudioResponse: + r"""Uploads audio for use in Golden Evaluations. Stores the audio in + the Cloud Storage bucket defined in + 'App.logging_settings.evaluation_audio_recording_config.gcs_bucket' + and returns a transcript. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_upload_evaluation_audio(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.UploadEvaluationAudioRequest( + app="app_value", + audio_content=b'audio_content_blob', + ) + + # Make the request + response = client.upload_evaluation_audio(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.UploadEvaluationAudioRequest, dict]): + The request object. Request message for + [EvaluationService.UploadEvaluationAudio][google.cloud.ces.v1beta.EvaluationService.UploadEvaluationAudio]. + app (str): + Required. The resource name of the App for which to + upload the evaluation audio. Format: + ``projects/{project}/locations/{location}/apps/{app}`` + + This corresponds to the ``app`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + audio_content (bytes): + Required. The raw audio bytes. + The format of the audio must be + single-channel LINEAR16 with a sample + rate of 16kHz (default + InputAudioConfig). + + This corresponds to the ``audio_content`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.UploadEvaluationAudioResponse: + Response message for + [EvaluationService.UploadEvaluationAudio][google.cloud.ces.v1beta.EvaluationService.UploadEvaluationAudio]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [app, audio_content] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.UploadEvaluationAudioRequest): + request = evaluation_service.UploadEvaluationAudioRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if app is not None: + request.app = app + if audio_content is not None: + request.audio_content = audio_content + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.upload_evaluation_audio] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("app", request.app),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_evaluation( + self, + request: Optional[ + Union[evaluation_service.CreateEvaluationRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + evaluation: Optional[gcc_evaluation.Evaluation] = None, + evaluation_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_evaluation.Evaluation: + r"""Creates an evaluation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_create_evaluation(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + evaluation = ces_v1beta.Evaluation() + evaluation.golden.turns.steps.user_input.text = "text_value" + evaluation.display_name = "display_name_value" + + request = ces_v1beta.CreateEvaluationRequest( + parent="parent_value", + evaluation=evaluation, + ) + + # Make the request + response = client.create_evaluation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.CreateEvaluationRequest, dict]): + The request object. Request message for + [EvaluationService.CreateEvaluation][google.cloud.ces.v1beta.EvaluationService.CreateEvaluation]. + parent (str): + Required. The app to create the evaluation for. Format: + ``projects/{project}/locations/{location}/apps/{app}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + evaluation (google.cloud.ces_v1beta.types.Evaluation): + Required. The evaluation to create. + This corresponds to the ``evaluation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + evaluation_id (str): + Optional. The ID to use for the + evaluation, which will become the final + component of the evaluation's resource + name. If not provided, a unique ID will + be automatically assigned for the + evaluation. + + This corresponds to the ``evaluation_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Evaluation: + An evaluation represents all of the + information needed to simulate and + evaluate an agent. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, evaluation, evaluation_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.CreateEvaluationRequest): + request = evaluation_service.CreateEvaluationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if evaluation is not None: + request.evaluation = evaluation + if evaluation_id is not None: + request.evaluation_id = evaluation_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_evaluation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def generate_evaluation( + self, + request: Optional[ + Union[evaluation_service.GenerateEvaluationRequest, dict] + ] = None, + *, + conversation: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Creates a golden evaluation from a conversation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_generate_evaluation(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.GenerateEvaluationRequest( + conversation="conversation_value", + ) + + # Make the request + operation = client.generate_evaluation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.GenerateEvaluationRequest, dict]): + The request object. Request message for + [EvaluationService.GenerateEvaluation][google.cloud.ces.v1beta.EvaluationService.GenerateEvaluation]. + conversation (str): + Required. The conversation to create the golden + evaluation for. Format: + ``projects/{project}/locations/{location}/apps/{app}/conversations/{conversation}`` + + This corresponds to the ``conversation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.ces_v1beta.types.Evaluation` An evaluation represents all of the information needed to simulate and + evaluate an agent. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [conversation] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.GenerateEvaluationRequest): + request = evaluation_service.GenerateEvaluationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if conversation is not None: + request.conversation = conversation + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.generate_evaluation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("conversation", request.conversation),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + evaluation.Evaluation, + metadata_type=evaluation_service.GenerateEvaluationOperationMetadata, + ) + + # Done; return the response. + return response + + def import_evaluations( + self, + request: Optional[ + Union[evaluation_service.ImportEvaluationsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Imports evaluations into the app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_import_evaluations(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ImportEvaluationsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.import_evaluations(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.ImportEvaluationsRequest, dict]): + The request object. Request message for + [EvaluationService.ImportEvaluations][google.cloud.ces.v1beta.EvaluationService.ImportEvaluations]. + parent (str): + Required. The app to import the evaluations into. + Format: + ``projects/{project}/locations/{location}/apps/{app}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.ces_v1beta.types.ImportEvaluationsResponse` Response message for + [EvaluationService.ImportEvaluations][google.cloud.ces.v1beta.EvaluationService.ImportEvaluations]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.ImportEvaluationsRequest): + request = evaluation_service.ImportEvaluationsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_evaluations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + evaluation_service.ImportEvaluationsResponse, + metadata_type=evaluation_service.ImportEvaluationsOperationMetadata, + ) + + # Done; return the response. + return response + + def create_evaluation_dataset( + self, + request: Optional[ + Union[evaluation_service.CreateEvaluationDatasetRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + evaluation_dataset: Optional[evaluation.EvaluationDataset] = None, + evaluation_dataset_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation.EvaluationDataset: + r"""Creates an evaluation dataset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_create_evaluation_dataset(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + evaluation_dataset = ces_v1beta.EvaluationDataset() + evaluation_dataset.display_name = "display_name_value" + + request = ces_v1beta.CreateEvaluationDatasetRequest( + parent="parent_value", + evaluation_dataset=evaluation_dataset, + ) + + # Make the request + response = client.create_evaluation_dataset(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.CreateEvaluationDatasetRequest, dict]): + The request object. Request message for + [EvaluationService.CreateEvaluationDataset][google.cloud.ces.v1beta.EvaluationService.CreateEvaluationDataset]. + parent (str): + Required. The app to create the evaluation for. Format: + ``projects/{project}/locations/{location}/apps/{app}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + evaluation_dataset (google.cloud.ces_v1beta.types.EvaluationDataset): + Required. The evaluation dataset to + create. + + This corresponds to the ``evaluation_dataset`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + evaluation_dataset_id (str): + Optional. The ID to use for the + evaluation dataset, which will become + the final component of the evaluation + dataset's resource name. If not + provided, a unique ID will be + automatically assigned for the + evaluation. + + This corresponds to the ``evaluation_dataset_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.EvaluationDataset: + An evaluation dataset represents a + set of evaluations that are grouped + together basaed on shared tags. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, evaluation_dataset, evaluation_dataset_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.CreateEvaluationDatasetRequest): + request = evaluation_service.CreateEvaluationDatasetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if evaluation_dataset is not None: + request.evaluation_dataset = evaluation_dataset + if evaluation_dataset_id is not None: + request.evaluation_dataset_id = evaluation_dataset_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.create_evaluation_dataset + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_evaluation( + self, + request: Optional[ + Union[evaluation_service.UpdateEvaluationRequest, dict] + ] = None, + *, + evaluation: Optional[gcc_evaluation.Evaluation] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_evaluation.Evaluation: + r"""Updates an evaluation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_update_evaluation(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + evaluation = ces_v1beta.Evaluation() + evaluation.golden.turns.steps.user_input.text = "text_value" + evaluation.display_name = "display_name_value" + + request = ces_v1beta.UpdateEvaluationRequest( + evaluation=evaluation, + ) + + # Make the request + response = client.update_evaluation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.UpdateEvaluationRequest, dict]): + The request object. Request message for + [EvaluationService.UpdateEvaluation][google.cloud.ces.v1beta.EvaluationService.UpdateEvaluation]. + evaluation (google.cloud.ces_v1beta.types.Evaluation): + Required. The evaluation to update. + This corresponds to the ``evaluation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to + control which fields get updated. If the + mask is not present, all fields will be + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Evaluation: + An evaluation represents all of the + information needed to simulate and + evaluate an agent. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [evaluation, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.UpdateEvaluationRequest): + request = evaluation_service.UpdateEvaluationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if evaluation is not None: + request.evaluation = evaluation + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_evaluation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("evaluation.name", request.evaluation.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_evaluation_dataset( + self, + request: Optional[ + Union[evaluation_service.UpdateEvaluationDatasetRequest, dict] + ] = None, + *, + evaluation_dataset: Optional[evaluation.EvaluationDataset] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation.EvaluationDataset: + r"""Updates an evaluation dataset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_update_evaluation_dataset(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + evaluation_dataset = ces_v1beta.EvaluationDataset() + evaluation_dataset.display_name = "display_name_value" + + request = ces_v1beta.UpdateEvaluationDatasetRequest( + evaluation_dataset=evaluation_dataset, + ) + + # Make the request + response = client.update_evaluation_dataset(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.UpdateEvaluationDatasetRequest, dict]): + The request object. Request message for + [EvaluationService.UpdateEvaluationDataset][google.cloud.ces.v1beta.EvaluationService.UpdateEvaluationDataset]. + evaluation_dataset (google.cloud.ces_v1beta.types.EvaluationDataset): + Required. The evaluation dataset to + update. + + This corresponds to the ``evaluation_dataset`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to + control which fields get updated. If the + mask is not present, all fields will be + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.EvaluationDataset: + An evaluation dataset represents a + set of evaluations that are grouped + together basaed on shared tags. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [evaluation_dataset, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.UpdateEvaluationDatasetRequest): + request = evaluation_service.UpdateEvaluationDatasetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if evaluation_dataset is not None: + request.evaluation_dataset = evaluation_dataset + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.update_evaluation_dataset + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("evaluation_dataset.name", request.evaluation_dataset.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_evaluation( + self, + request: Optional[ + Union[evaluation_service.DeleteEvaluationRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes an evaluation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_delete_evaluation(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteEvaluationRequest( + name="name_value", + ) + + # Make the request + client.delete_evaluation(request=request) + + Args: + request (Union[google.cloud.ces_v1beta.types.DeleteEvaluationRequest, dict]): + The request object. Request message for + [EvaluationService.DeleteEvaluation][google.cloud.ces.v1beta.EvaluationService.DeleteEvaluation]. + name (str): + Required. The resource name of the + evaluation to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.DeleteEvaluationRequest): + request = evaluation_service.DeleteEvaluationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_evaluation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def delete_evaluation_result( + self, + request: Optional[ + Union[evaluation_service.DeleteEvaluationResultRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes an evaluation result. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_delete_evaluation_result(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteEvaluationResultRequest( + name="name_value", + ) + + # Make the request + client.delete_evaluation_result(request=request) + + Args: + request (Union[google.cloud.ces_v1beta.types.DeleteEvaluationResultRequest, dict]): + The request object. Request message for + [EvaluationService.DeleteEvaluationResult][google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationResult]. + name (str): + Required. The resource name of the + evaluation result to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.DeleteEvaluationResultRequest): + request = evaluation_service.DeleteEvaluationResultRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_evaluation_result] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def delete_evaluation_dataset( + self, + request: Optional[ + Union[evaluation_service.DeleteEvaluationDatasetRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes an evaluation dataset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_delete_evaluation_dataset(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteEvaluationDatasetRequest( + name="name_value", + ) + + # Make the request + client.delete_evaluation_dataset(request=request) + + Args: + request (Union[google.cloud.ces_v1beta.types.DeleteEvaluationDatasetRequest, dict]): + The request object. Request message for + [EvaluationService.DeleteEvaluationDataset][google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationDataset]. + name (str): + Required. The resource name of the + evaluation dataset to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.DeleteEvaluationDatasetRequest): + request = evaluation_service.DeleteEvaluationDatasetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.delete_evaluation_dataset + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def delete_evaluation_run( + self, + request: Optional[ + Union[evaluation_service.DeleteEvaluationRunRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes an evaluation run. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_delete_evaluation_run(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteEvaluationRunRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_evaluation_run(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.DeleteEvaluationRunRequest, dict]): + The request object. Request message for + [EvaluationService.DeleteEvaluationRun][google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationRun]. + name (str): + Required. The resource name of the + evaluation run to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.DeleteEvaluationRunRequest): + request = evaluation_service.DeleteEvaluationRunRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_evaluation_run] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=evaluation_service.DeleteEvaluationRunOperationMetadata, + ) + + # Done; return the response. + return response + + def get_evaluation( + self, + request: Optional[Union[evaluation_service.GetEvaluationRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation.Evaluation: + r"""Gets details of the specified evaluation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_get_evaluation(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.GetEvaluationRequest( + name="name_value", + ) + + # Make the request + response = client.get_evaluation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.GetEvaluationRequest, dict]): + The request object. Request message for + [EvaluationService.GetEvaluation][google.cloud.ces.v1beta.EvaluationService.GetEvaluation]. + name (str): + Required. The resource name of the + evaluation to retrieve. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.Evaluation: + An evaluation represents all of the + information needed to simulate and + evaluate an agent. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.GetEvaluationRequest): + request = evaluation_service.GetEvaluationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_evaluation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_evaluation_result( + self, + request: Optional[ + Union[evaluation_service.GetEvaluationResultRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation.EvaluationResult: + r"""Gets details of the specified evaluation result. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_get_evaluation_result(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.GetEvaluationResultRequest( + name="name_value", + ) + + # Make the request + response = client.get_evaluation_result(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.GetEvaluationResultRequest, dict]): + The request object. Request message for + [EvaluationService.GetEvaluationResult][google.cloud.ces.v1beta.EvaluationService.GetEvaluationResult]. + name (str): + Required. The resource name of the + evaluation result to retrieve. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.EvaluationResult: + An evaluation result represents the + output of running an Evaluation. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.GetEvaluationResultRequest): + request = evaluation_service.GetEvaluationResultRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_evaluation_result] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_evaluation_dataset( + self, + request: Optional[ + Union[evaluation_service.GetEvaluationDatasetRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation.EvaluationDataset: + r"""Gets details of the specified evaluation dataset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_get_evaluation_dataset(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.GetEvaluationDatasetRequest( + name="name_value", + ) + + # Make the request + response = client.get_evaluation_dataset(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.GetEvaluationDatasetRequest, dict]): + The request object. Request message for + [EvaluationService.GetEvaluationDataset][google.cloud.ces.v1beta.EvaluationService.GetEvaluationDataset]. + name (str): + Required. The resource name of the + evaluation dataset to retrieve. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.EvaluationDataset: + An evaluation dataset represents a + set of evaluations that are grouped + together basaed on shared tags. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.GetEvaluationDatasetRequest): + request = evaluation_service.GetEvaluationDatasetRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_evaluation_dataset] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_evaluation_run( + self, + request: Optional[ + Union[evaluation_service.GetEvaluationRunRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation.EvaluationRun: + r"""Gets details of the specified evaluation run. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_get_evaluation_run(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.GetEvaluationRunRequest( + name="name_value", + ) + + # Make the request + response = client.get_evaluation_run(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.GetEvaluationRunRequest, dict]): + The request object. Request message for + [EvaluationService.GetEvaluationRun][google.cloud.ces.v1beta.EvaluationService.GetEvaluationRun]. + name (str): + Required. The resource name of the + evaluation run to retrieve. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.EvaluationRun: + An evaluation run represents an all + the evaluation results from an + evaluation execution. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.GetEvaluationRunRequest): + request = evaluation_service.GetEvaluationRunRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_evaluation_run] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_evaluations( + self, + request: Optional[ + Union[evaluation_service.ListEvaluationsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListEvaluationsPager: + r"""Lists all evaluations in the given app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_list_evaluations(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ListEvaluationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_evaluations(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.ListEvaluationsRequest, dict]): + The request object. Request message for + [EvaluationService.ListEvaluations][google.cloud.ces.v1beta.EvaluationService.ListEvaluations]. + parent (str): + Required. The resource name of the + app to list evaluations from. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.services.evaluation_service.pagers.ListEvaluationsPager: + Response message for + [EvaluationService.ListEvaluations][google.cloud.ces.v1beta.EvaluationService.ListEvaluations]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.ListEvaluationsRequest): + request = evaluation_service.ListEvaluationsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_evaluations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListEvaluationsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_evaluation_results( + self, + request: Optional[ + Union[evaluation_service.ListEvaluationResultsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListEvaluationResultsPager: + r"""Lists all evaluation results for a given evaluation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_list_evaluation_results(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ListEvaluationResultsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_evaluation_results(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.ListEvaluationResultsRequest, dict]): + The request object. Request message for + [EvaluationService.ListEvaluationResults][google.cloud.ces.v1beta.EvaluationService.ListEvaluationResults]. + parent (str): + Required. The resource name of the evaluation to list + evaluation results from. To filter by evaluation run, + use ``-`` as the evaluation ID and specify the + evaluation run ID in the filter. For example: + ``projects/{project}/locations/{location}/apps/{app}/evaluations/-`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.services.evaluation_service.pagers.ListEvaluationResultsPager: + Response message for + [EvaluationService.ListEvaluationResults][google.cloud.ces.v1beta.EvaluationService.ListEvaluationResults]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.ListEvaluationResultsRequest): + request = evaluation_service.ListEvaluationResultsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_evaluation_results] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListEvaluationResultsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_evaluation_datasets( + self, + request: Optional[ + Union[evaluation_service.ListEvaluationDatasetsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListEvaluationDatasetsPager: + r"""Lists all evaluation datasets in the given app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_list_evaluation_datasets(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ListEvaluationDatasetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_evaluation_datasets(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.ListEvaluationDatasetsRequest, dict]): + The request object. Request message for + [EvaluationService.ListEvaluationDatasets][google.cloud.ces.v1beta.EvaluationService.ListEvaluationDatasets]. + parent (str): + Required. The resource name of the + app to list evaluation datasets from. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.services.evaluation_service.pagers.ListEvaluationDatasetsPager: + Response message for + [EvaluationService.ListEvaluationDatasets][google.cloud.ces.v1beta.EvaluationService.ListEvaluationDatasets]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.ListEvaluationDatasetsRequest): + request = evaluation_service.ListEvaluationDatasetsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_evaluation_datasets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListEvaluationDatasetsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_evaluation_runs( + self, + request: Optional[ + Union[evaluation_service.ListEvaluationRunsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListEvaluationRunsPager: + r"""Lists all evaluation runs in the given app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_list_evaluation_runs(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ListEvaluationRunsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_evaluation_runs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.ListEvaluationRunsRequest, dict]): + The request object. Request message for + [EvaluationService.ListEvaluationRuns][google.cloud.ces.v1beta.EvaluationService.ListEvaluationRuns]. + parent (str): + Required. The resource name of the + app to list evaluation runs from. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.services.evaluation_service.pagers.ListEvaluationRunsPager: + Response message for + [EvaluationService.ListEvaluationRuns][google.cloud.ces.v1beta.EvaluationService.ListEvaluationRuns]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.ListEvaluationRunsRequest): + request = evaluation_service.ListEvaluationRunsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_evaluation_runs] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListEvaluationRunsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_evaluation_expectations( + self, + request: Optional[ + Union[evaluation_service.ListEvaluationExpectationsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListEvaluationExpectationsPager: + r"""Lists all evaluation expectations in the given app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_list_evaluation_expectations(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ListEvaluationExpectationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_evaluation_expectations(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.ListEvaluationExpectationsRequest, dict]): + The request object. Request message for + [EvaluationService.ListEvaluationExpectations][google.cloud.ces.v1beta.EvaluationService.ListEvaluationExpectations]. + parent (str): + Required. The resource name of the + app to list evaluation expectations + from. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.services.evaluation_service.pagers.ListEvaluationExpectationsPager: + Response message for + [EvaluationService.ListEvaluationExpectations][google.cloud.ces.v1beta.EvaluationService.ListEvaluationExpectations]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, evaluation_service.ListEvaluationExpectationsRequest + ): + request = evaluation_service.ListEvaluationExpectationsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.list_evaluation_expectations + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListEvaluationExpectationsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_evaluation_expectation( + self, + request: Optional[ + Union[evaluation_service.GetEvaluationExpectationRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation.EvaluationExpectation: + r"""Gets details of the specified evaluation expectation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_get_evaluation_expectation(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.GetEvaluationExpectationRequest( + name="name_value", + ) + + # Make the request + response = client.get_evaluation_expectation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.GetEvaluationExpectationRequest, dict]): + The request object. Request message for + [EvaluationService.GetEvaluationExpectation][google.cloud.ces.v1beta.EvaluationService.GetEvaluationExpectation]. + name (str): + Required. The resource name of the + evaluation expectation to retrieve. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.EvaluationExpectation: + An evaluation expectation represents + a specific criteria to evaluate against. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.GetEvaluationExpectationRequest): + request = evaluation_service.GetEvaluationExpectationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.get_evaluation_expectation + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_evaluation_expectation( + self, + request: Optional[ + Union[evaluation_service.CreateEvaluationExpectationRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + evaluation_expectation: Optional[evaluation.EvaluationExpectation] = None, + evaluation_expectation_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation.EvaluationExpectation: + r"""Creates an evaluation expectation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_create_evaluation_expectation(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + evaluation_expectation = ces_v1beta.EvaluationExpectation() + evaluation_expectation.llm_criteria.prompt = "prompt_value" + evaluation_expectation.display_name = "display_name_value" + + request = ces_v1beta.CreateEvaluationExpectationRequest( + parent="parent_value", + evaluation_expectation=evaluation_expectation, + ) + + # Make the request + response = client.create_evaluation_expectation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.CreateEvaluationExpectationRequest, dict]): + The request object. Request message for + [EvaluationService.CreateEvaluationExpectation][google.cloud.ces.v1beta.EvaluationService.CreateEvaluationExpectation]. + parent (str): + Required. The app to create the evaluation expectation + for. Format: + ``projects/{project}/locations/{location}/apps/{app}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + evaluation_expectation (google.cloud.ces_v1beta.types.EvaluationExpectation): + Required. The evaluation expectation + to create. + + This corresponds to the ``evaluation_expectation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + evaluation_expectation_id (str): + Optional. The ID to use for the + evaluation expectation, which will + become the final component of the + evaluation expectation's resource name. + If not provided, a unique ID will be + automatically assigned for the + evaluation expectation. + + This corresponds to the ``evaluation_expectation_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.EvaluationExpectation: + An evaluation expectation represents + a specific criteria to evaluate against. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, evaluation_expectation, evaluation_expectation_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, evaluation_service.CreateEvaluationExpectationRequest + ): + request = evaluation_service.CreateEvaluationExpectationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if evaluation_expectation is not None: + request.evaluation_expectation = evaluation_expectation + if evaluation_expectation_id is not None: + request.evaluation_expectation_id = evaluation_expectation_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.create_evaluation_expectation + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_evaluation_expectation( + self, + request: Optional[ + Union[evaluation_service.UpdateEvaluationExpectationRequest, dict] + ] = None, + *, + evaluation_expectation: Optional[evaluation.EvaluationExpectation] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation.EvaluationExpectation: + r"""Updates an evaluation expectation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_update_evaluation_expectation(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + evaluation_expectation = ces_v1beta.EvaluationExpectation() + evaluation_expectation.llm_criteria.prompt = "prompt_value" + evaluation_expectation.display_name = "display_name_value" + + request = ces_v1beta.UpdateEvaluationExpectationRequest( + evaluation_expectation=evaluation_expectation, + ) + + # Make the request + response = client.update_evaluation_expectation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.UpdateEvaluationExpectationRequest, dict]): + The request object. Request message for + [EvaluationService.UpdateEvaluationExpectation][google.cloud.ces.v1beta.EvaluationService.UpdateEvaluationExpectation]. + evaluation_expectation (google.cloud.ces_v1beta.types.EvaluationExpectation): + Required. The evaluation expectation + to update. + + This corresponds to the ``evaluation_expectation`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to + control which fields get updated. If the + mask is not present, all fields will be + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.EvaluationExpectation: + An evaluation expectation represents + a specific criteria to evaluate against. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [evaluation_expectation, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, evaluation_service.UpdateEvaluationExpectationRequest + ): + request = evaluation_service.UpdateEvaluationExpectationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if evaluation_expectation is not None: + request.evaluation_expectation = evaluation_expectation + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.update_evaluation_expectation + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("evaluation_expectation.name", request.evaluation_expectation.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_evaluation_expectation( + self, + request: Optional[ + Union[evaluation_service.DeleteEvaluationExpectationRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes an evaluation expectation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_delete_evaluation_expectation(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteEvaluationExpectationRequest( + name="name_value", + ) + + # Make the request + client.delete_evaluation_expectation(request=request) + + Args: + request (Union[google.cloud.ces_v1beta.types.DeleteEvaluationExpectationRequest, dict]): + The request object. Request message for + [EvaluationService.DeleteEvaluationExpectation][google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationExpectation]. + name (str): + Required. The resource name of the + evaluation expectation to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, evaluation_service.DeleteEvaluationExpectationRequest + ): + request = evaluation_service.DeleteEvaluationExpectationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.delete_evaluation_expectation + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def create_scheduled_evaluation_run( + self, + request: Optional[ + Union[evaluation_service.CreateScheduledEvaluationRunRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + scheduled_evaluation_run: Optional[evaluation.ScheduledEvaluationRun] = None, + scheduled_evaluation_run_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation.ScheduledEvaluationRun: + r"""Creates a scheduled evaluation run. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_create_scheduled_evaluation_run(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + scheduled_evaluation_run = ces_v1beta.ScheduledEvaluationRun() + scheduled_evaluation_run.display_name = "display_name_value" + scheduled_evaluation_run.request.app = "app_value" + scheduled_evaluation_run.scheduling_config.frequency = "BIWEEKLY" + + request = ces_v1beta.CreateScheduledEvaluationRunRequest( + parent="parent_value", + scheduled_evaluation_run=scheduled_evaluation_run, + ) + + # Make the request + response = client.create_scheduled_evaluation_run(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.CreateScheduledEvaluationRunRequest, dict]): + The request object. Request message for + [EvaluationService.CreateScheduledEvaluationRun][google.cloud.ces.v1beta.EvaluationService.CreateScheduledEvaluationRun]. + parent (str): + Required. The app to create the scheduled evaluation run + for. Format: + ``projects/{project}/locations/{location}/apps/{app}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + scheduled_evaluation_run (google.cloud.ces_v1beta.types.ScheduledEvaluationRun): + Required. The scheduled evaluation + run to create. + + This corresponds to the ``scheduled_evaluation_run`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + scheduled_evaluation_run_id (str): + Optional. The ID to use for the + scheduled evaluation run, which will + become the final component of the + scheduled evaluation run's resource + name. If not provided, a unique ID will + be automatically assigned. + + This corresponds to the ``scheduled_evaluation_run_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.ScheduledEvaluationRun: + Represents a scheduled evaluation run + configuration. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [ + parent, + scheduled_evaluation_run, + scheduled_evaluation_run_id, + ] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, evaluation_service.CreateScheduledEvaluationRunRequest + ): + request = evaluation_service.CreateScheduledEvaluationRunRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if scheduled_evaluation_run is not None: + request.scheduled_evaluation_run = scheduled_evaluation_run + if scheduled_evaluation_run_id is not None: + request.scheduled_evaluation_run_id = scheduled_evaluation_run_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.create_scheduled_evaluation_run + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_scheduled_evaluation_run( + self, + request: Optional[ + Union[evaluation_service.GetScheduledEvaluationRunRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation.ScheduledEvaluationRun: + r"""Gets details of the specified scheduled evaluation + run. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_get_scheduled_evaluation_run(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.GetScheduledEvaluationRunRequest( + name="name_value", + ) + + # Make the request + response = client.get_scheduled_evaluation_run(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.GetScheduledEvaluationRunRequest, dict]): + The request object. Request message for + [EvaluationService.GetScheduledEvaluationRun][google.cloud.ces.v1beta.EvaluationService.GetScheduledEvaluationRun]. + name (str): + Required. The resource name of the + scheduled evaluation run to retrieve. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.ScheduledEvaluationRun: + Represents a scheduled evaluation run + configuration. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.GetScheduledEvaluationRunRequest): + request = evaluation_service.GetScheduledEvaluationRunRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.get_scheduled_evaluation_run + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_scheduled_evaluation_runs( + self, + request: Optional[ + Union[evaluation_service.ListScheduledEvaluationRunsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListScheduledEvaluationRunsPager: + r"""Lists all scheduled evaluation runs in the given app. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_list_scheduled_evaluation_runs(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ListScheduledEvaluationRunsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_scheduled_evaluation_runs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.ListScheduledEvaluationRunsRequest, dict]): + The request object. Request message for + [EvaluationService.ListScheduledEvaluationRuns][google.cloud.ces.v1beta.EvaluationService.ListScheduledEvaluationRuns]. + parent (str): + Required. The resource name of the + app to list scheduled evaluation runs + from. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.services.evaluation_service.pagers.ListScheduledEvaluationRunsPager: + Response message for + [EvaluationService.ListScheduledEvaluationRuns][google.cloud.ces.v1beta.EvaluationService.ListScheduledEvaluationRuns]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, evaluation_service.ListScheduledEvaluationRunsRequest + ): + request = evaluation_service.ListScheduledEvaluationRunsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.list_scheduled_evaluation_runs + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListScheduledEvaluationRunsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_scheduled_evaluation_run( + self, + request: Optional[ + Union[evaluation_service.UpdateScheduledEvaluationRunRequest, dict] + ] = None, + *, + scheduled_evaluation_run: Optional[evaluation.ScheduledEvaluationRun] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation.ScheduledEvaluationRun: + r"""Updates a scheduled evaluation run. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_update_scheduled_evaluation_run(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + scheduled_evaluation_run = ces_v1beta.ScheduledEvaluationRun() + scheduled_evaluation_run.display_name = "display_name_value" + scheduled_evaluation_run.request.app = "app_value" + scheduled_evaluation_run.scheduling_config.frequency = "BIWEEKLY" + + request = ces_v1beta.UpdateScheduledEvaluationRunRequest( + scheduled_evaluation_run=scheduled_evaluation_run, + ) + + # Make the request + response = client.update_scheduled_evaluation_run(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.UpdateScheduledEvaluationRunRequest, dict]): + The request object. Request message for + [EvaluationService.UpdateScheduledEvaluationRun][google.cloud.ces.v1beta.EvaluationService.UpdateScheduledEvaluationRun]. + scheduled_evaluation_run (google.cloud.ces_v1beta.types.ScheduledEvaluationRun): + Required. The scheduled evaluation + run to update. + + This corresponds to the ``scheduled_evaluation_run`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to + control which fields get updated. If the + mask is not present, all fields will be + updated. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.ScheduledEvaluationRun: + Represents a scheduled evaluation run + configuration. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [scheduled_evaluation_run, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, evaluation_service.UpdateScheduledEvaluationRunRequest + ): + request = evaluation_service.UpdateScheduledEvaluationRunRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if scheduled_evaluation_run is not None: + request.scheduled_evaluation_run = scheduled_evaluation_run + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.update_scheduled_evaluation_run + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ( + "scheduled_evaluation_run.name", + request.scheduled_evaluation_run.name, + ), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_scheduled_evaluation_run( + self, + request: Optional[ + Union[evaluation_service.DeleteScheduledEvaluationRunRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a scheduled evaluation run. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_delete_scheduled_evaluation_run(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteScheduledEvaluationRunRequest( + name="name_value", + ) + + # Make the request + client.delete_scheduled_evaluation_run(request=request) + + Args: + request (Union[google.cloud.ces_v1beta.types.DeleteScheduledEvaluationRunRequest, dict]): + The request object. Request message for + [EvaluationService.DeleteScheduledEvaluationRun][google.cloud.ces.v1beta.EvaluationService.DeleteScheduledEvaluationRun]. + name (str): + Required. The resource name of the + scheduled evaluation run to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, evaluation_service.DeleteScheduledEvaluationRunRequest + ): + request = evaluation_service.DeleteScheduledEvaluationRunRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.delete_scheduled_evaluation_run + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def test_persona_voice( + self, + request: Optional[ + Union[evaluation_service.TestPersonaVoiceRequest, dict] + ] = None, + *, + app: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation_service.TestPersonaVoiceResponse: + r"""Tests the voice of a persona. Also accepts a default + persona. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_test_persona_voice(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.TestPersonaVoiceRequest( + app="app_value", + persona_id="persona_id_value", + text="text_value", + ) + + # Make the request + response = client.test_persona_voice(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.TestPersonaVoiceRequest, dict]): + The request object. Request message for + [EvaluationService.TestPersonaVoice][google.cloud.ces.v1beta.EvaluationService.TestPersonaVoice]. + app (str): + Required. the resource name of the app to test the + persona voice for. Format: + ``projects/{project}/locations/{location}/apps/{app}`` + + This corresponds to the ``app`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.TestPersonaVoiceResponse: + Response message for + [EvaluationService.TestPersonaVoice][google.cloud.ces.v1beta.EvaluationService.TestPersonaVoice]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [app] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, evaluation_service.TestPersonaVoiceRequest): + request = evaluation_service.TestPersonaVoiceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if app is not None: + request.app = app + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_persona_voice] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("app", request.app),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "EvaluationServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("EvaluationServiceClient",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/pagers.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/pagers.py new file mode 100644 index 000000000000..1a840c9de6ca --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/pagers.py @@ -0,0 +1,995 @@ +# -*- coding: utf-8 -*- +# 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 typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.cloud.ces_v1beta.types import evaluation, evaluation_service + + +class ListEvaluationsPager: + """A pager for iterating through ``list_evaluations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.ces_v1beta.types.ListEvaluationsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``evaluations`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEvaluations`` requests and continue to iterate + through the ``evaluations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.ces_v1beta.types.ListEvaluationsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., evaluation_service.ListEvaluationsResponse], + request: evaluation_service.ListEvaluationsRequest, + response: evaluation_service.ListEvaluationsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.ces_v1beta.types.ListEvaluationsRequest): + The initial request object. + response (google.cloud.ces_v1beta.types.ListEvaluationsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = evaluation_service.ListEvaluationsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[evaluation_service.ListEvaluationsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[evaluation.Evaluation]: + for page in self.pages: + yield from page.evaluations + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListEvaluationsAsyncPager: + """A pager for iterating through ``list_evaluations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.ces_v1beta.types.ListEvaluationsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``evaluations`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEvaluations`` requests and continue to iterate + through the ``evaluations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.ces_v1beta.types.ListEvaluationsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[evaluation_service.ListEvaluationsResponse]], + request: evaluation_service.ListEvaluationsRequest, + response: evaluation_service.ListEvaluationsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.ces_v1beta.types.ListEvaluationsRequest): + The initial request object. + response (google.cloud.ces_v1beta.types.ListEvaluationsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = evaluation_service.ListEvaluationsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[evaluation_service.ListEvaluationsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[evaluation.Evaluation]: + async def async_generator(): + async for page in self.pages: + for response in page.evaluations: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListEvaluationResultsPager: + """A pager for iterating through ``list_evaluation_results`` requests. + + This class thinly wraps an initial + :class:`google.cloud.ces_v1beta.types.ListEvaluationResultsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``evaluation_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEvaluationResults`` requests and continue to iterate + through the ``evaluation_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.ces_v1beta.types.ListEvaluationResultsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., evaluation_service.ListEvaluationResultsResponse], + request: evaluation_service.ListEvaluationResultsRequest, + response: evaluation_service.ListEvaluationResultsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.ces_v1beta.types.ListEvaluationResultsRequest): + The initial request object. + response (google.cloud.ces_v1beta.types.ListEvaluationResultsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = evaluation_service.ListEvaluationResultsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[evaluation_service.ListEvaluationResultsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[evaluation.EvaluationResult]: + for page in self.pages: + yield from page.evaluation_results + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListEvaluationResultsAsyncPager: + """A pager for iterating through ``list_evaluation_results`` requests. + + This class thinly wraps an initial + :class:`google.cloud.ces_v1beta.types.ListEvaluationResultsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``evaluation_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEvaluationResults`` requests and continue to iterate + through the ``evaluation_results`` field on the + corresponding responses. + + All the usual :class:`google.cloud.ces_v1beta.types.ListEvaluationResultsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., Awaitable[evaluation_service.ListEvaluationResultsResponse] + ], + request: evaluation_service.ListEvaluationResultsRequest, + response: evaluation_service.ListEvaluationResultsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.ces_v1beta.types.ListEvaluationResultsRequest): + The initial request object. + response (google.cloud.ces_v1beta.types.ListEvaluationResultsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = evaluation_service.ListEvaluationResultsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[evaluation_service.ListEvaluationResultsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[evaluation.EvaluationResult]: + async def async_generator(): + async for page in self.pages: + for response in page.evaluation_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListEvaluationDatasetsPager: + """A pager for iterating through ``list_evaluation_datasets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.ces_v1beta.types.ListEvaluationDatasetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``evaluation_datasets`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEvaluationDatasets`` requests and continue to iterate + through the ``evaluation_datasets`` field on the + corresponding responses. + + All the usual :class:`google.cloud.ces_v1beta.types.ListEvaluationDatasetsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., evaluation_service.ListEvaluationDatasetsResponse], + request: evaluation_service.ListEvaluationDatasetsRequest, + response: evaluation_service.ListEvaluationDatasetsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.ces_v1beta.types.ListEvaluationDatasetsRequest): + The initial request object. + response (google.cloud.ces_v1beta.types.ListEvaluationDatasetsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = evaluation_service.ListEvaluationDatasetsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[evaluation_service.ListEvaluationDatasetsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[evaluation.EvaluationDataset]: + for page in self.pages: + yield from page.evaluation_datasets + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListEvaluationDatasetsAsyncPager: + """A pager for iterating through ``list_evaluation_datasets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.ces_v1beta.types.ListEvaluationDatasetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``evaluation_datasets`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEvaluationDatasets`` requests and continue to iterate + through the ``evaluation_datasets`` field on the + corresponding responses. + + All the usual :class:`google.cloud.ces_v1beta.types.ListEvaluationDatasetsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., Awaitable[evaluation_service.ListEvaluationDatasetsResponse] + ], + request: evaluation_service.ListEvaluationDatasetsRequest, + response: evaluation_service.ListEvaluationDatasetsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.ces_v1beta.types.ListEvaluationDatasetsRequest): + The initial request object. + response (google.cloud.ces_v1beta.types.ListEvaluationDatasetsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = evaluation_service.ListEvaluationDatasetsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[evaluation_service.ListEvaluationDatasetsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[evaluation.EvaluationDataset]: + async def async_generator(): + async for page in self.pages: + for response in page.evaluation_datasets: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListEvaluationRunsPager: + """A pager for iterating through ``list_evaluation_runs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.ces_v1beta.types.ListEvaluationRunsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``evaluation_runs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEvaluationRuns`` requests and continue to iterate + through the ``evaluation_runs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.ces_v1beta.types.ListEvaluationRunsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., evaluation_service.ListEvaluationRunsResponse], + request: evaluation_service.ListEvaluationRunsRequest, + response: evaluation_service.ListEvaluationRunsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.ces_v1beta.types.ListEvaluationRunsRequest): + The initial request object. + response (google.cloud.ces_v1beta.types.ListEvaluationRunsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = evaluation_service.ListEvaluationRunsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[evaluation_service.ListEvaluationRunsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[evaluation.EvaluationRun]: + for page in self.pages: + yield from page.evaluation_runs + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListEvaluationRunsAsyncPager: + """A pager for iterating through ``list_evaluation_runs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.ces_v1beta.types.ListEvaluationRunsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``evaluation_runs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEvaluationRuns`` requests and continue to iterate + through the ``evaluation_runs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.ces_v1beta.types.ListEvaluationRunsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[evaluation_service.ListEvaluationRunsResponse]], + request: evaluation_service.ListEvaluationRunsRequest, + response: evaluation_service.ListEvaluationRunsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.ces_v1beta.types.ListEvaluationRunsRequest): + The initial request object. + response (google.cloud.ces_v1beta.types.ListEvaluationRunsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = evaluation_service.ListEvaluationRunsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[evaluation_service.ListEvaluationRunsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[evaluation.EvaluationRun]: + async def async_generator(): + async for page in self.pages: + for response in page.evaluation_runs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListEvaluationExpectationsPager: + """A pager for iterating through ``list_evaluation_expectations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.ces_v1beta.types.ListEvaluationExpectationsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``evaluation_expectations`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEvaluationExpectations`` requests and continue to iterate + through the ``evaluation_expectations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.ces_v1beta.types.ListEvaluationExpectationsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., evaluation_service.ListEvaluationExpectationsResponse], + request: evaluation_service.ListEvaluationExpectationsRequest, + response: evaluation_service.ListEvaluationExpectationsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.ces_v1beta.types.ListEvaluationExpectationsRequest): + The initial request object. + response (google.cloud.ces_v1beta.types.ListEvaluationExpectationsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = evaluation_service.ListEvaluationExpectationsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[evaluation_service.ListEvaluationExpectationsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[evaluation.EvaluationExpectation]: + for page in self.pages: + yield from page.evaluation_expectations + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListEvaluationExpectationsAsyncPager: + """A pager for iterating through ``list_evaluation_expectations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.ces_v1beta.types.ListEvaluationExpectationsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``evaluation_expectations`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEvaluationExpectations`` requests and continue to iterate + through the ``evaluation_expectations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.ces_v1beta.types.ListEvaluationExpectationsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., Awaitable[evaluation_service.ListEvaluationExpectationsResponse] + ], + request: evaluation_service.ListEvaluationExpectationsRequest, + response: evaluation_service.ListEvaluationExpectationsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.ces_v1beta.types.ListEvaluationExpectationsRequest): + The initial request object. + response (google.cloud.ces_v1beta.types.ListEvaluationExpectationsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = evaluation_service.ListEvaluationExpectationsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[evaluation_service.ListEvaluationExpectationsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[evaluation.EvaluationExpectation]: + async def async_generator(): + async for page in self.pages: + for response in page.evaluation_expectations: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListScheduledEvaluationRunsPager: + """A pager for iterating through ``list_scheduled_evaluation_runs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.ces_v1beta.types.ListScheduledEvaluationRunsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``scheduled_evaluation_runs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListScheduledEvaluationRuns`` requests and continue to iterate + through the ``scheduled_evaluation_runs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.ces_v1beta.types.ListScheduledEvaluationRunsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., evaluation_service.ListScheduledEvaluationRunsResponse], + request: evaluation_service.ListScheduledEvaluationRunsRequest, + response: evaluation_service.ListScheduledEvaluationRunsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.ces_v1beta.types.ListScheduledEvaluationRunsRequest): + The initial request object. + response (google.cloud.ces_v1beta.types.ListScheduledEvaluationRunsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = evaluation_service.ListScheduledEvaluationRunsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[evaluation_service.ListScheduledEvaluationRunsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[evaluation.ScheduledEvaluationRun]: + for page in self.pages: + yield from page.scheduled_evaluation_runs + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListScheduledEvaluationRunsAsyncPager: + """A pager for iterating through ``list_scheduled_evaluation_runs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.ces_v1beta.types.ListScheduledEvaluationRunsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``scheduled_evaluation_runs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListScheduledEvaluationRuns`` requests and continue to iterate + through the ``scheduled_evaluation_runs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.ces_v1beta.types.ListScheduledEvaluationRunsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., Awaitable[evaluation_service.ListScheduledEvaluationRunsResponse] + ], + request: evaluation_service.ListScheduledEvaluationRunsRequest, + response: evaluation_service.ListScheduledEvaluationRunsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.ces_v1beta.types.ListScheduledEvaluationRunsRequest): + The initial request object. + response (google.cloud.ces_v1beta.types.ListScheduledEvaluationRunsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = evaluation_service.ListScheduledEvaluationRunsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[evaluation_service.ListScheduledEvaluationRunsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[evaluation.ScheduledEvaluationRun]: + async def async_generator(): + async for page in self.pages: + for response in page.scheduled_evaluation_runs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/transports/README.rst b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/transports/README.rst new file mode 100644 index 000000000000..b012f0c5c184 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`EvaluationServiceTransport` is the ABC for all transports. +- public child `EvaluationServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `EvaluationServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseEvaluationServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `EvaluationServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/transports/__init__.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/transports/__init__.py new file mode 100644 index 000000000000..c3cac92e11d7 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# 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 collections import OrderedDict +from typing import Dict, Type + +from .base import EvaluationServiceTransport +from .grpc import EvaluationServiceGrpcTransport +from .grpc_asyncio import EvaluationServiceGrpcAsyncIOTransport +from .rest import EvaluationServiceRestInterceptor, EvaluationServiceRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[EvaluationServiceTransport]] +_transport_registry["grpc"] = EvaluationServiceGrpcTransport +_transport_registry["grpc_asyncio"] = EvaluationServiceGrpcAsyncIOTransport +_transport_registry["rest"] = EvaluationServiceRestTransport + +__all__ = ( + "EvaluationServiceTransport", + "EvaluationServiceGrpcTransport", + "EvaluationServiceGrpcAsyncIOTransport", + "EvaluationServiceRestTransport", + "EvaluationServiceRestInterceptor", +) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/transports/base.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/transports/base.py new file mode 100644 index 000000000000..3d533cf7d153 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/transports/base.py @@ -0,0 +1,733 @@ +# -*- coding: utf-8 -*- +# 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. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +import google.auth # type: ignore +import google.protobuf +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.ces_v1beta import gapic_version as package_version +from google.cloud.ces_v1beta.types import evaluation, evaluation_service +from google.cloud.ces_v1beta.types import evaluation as gcc_evaluation + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class EvaluationServiceTransport(abc.ABC): + """Abstract transport class for EvaluationService.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/ces", + "https://www.googleapis.com/auth/cloud-platform", + ) + + DEFAULT_HOST: str = "ces.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'ces.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.run_evaluation: gapic_v1.method.wrap_method( + self.run_evaluation, + default_timeout=None, + client_info=client_info, + ), + self.upload_evaluation_audio: gapic_v1.method.wrap_method( + self.upload_evaluation_audio, + default_timeout=None, + client_info=client_info, + ), + self.create_evaluation: gapic_v1.method.wrap_method( + self.create_evaluation, + default_timeout=None, + client_info=client_info, + ), + self.generate_evaluation: gapic_v1.method.wrap_method( + self.generate_evaluation, + default_timeout=None, + client_info=client_info, + ), + self.import_evaluations: gapic_v1.method.wrap_method( + self.import_evaluations, + default_timeout=None, + client_info=client_info, + ), + self.create_evaluation_dataset: gapic_v1.method.wrap_method( + self.create_evaluation_dataset, + default_timeout=None, + client_info=client_info, + ), + self.update_evaluation: gapic_v1.method.wrap_method( + self.update_evaluation, + default_timeout=None, + client_info=client_info, + ), + self.update_evaluation_dataset: gapic_v1.method.wrap_method( + self.update_evaluation_dataset, + default_timeout=None, + client_info=client_info, + ), + self.delete_evaluation: gapic_v1.method.wrap_method( + self.delete_evaluation, + default_timeout=None, + client_info=client_info, + ), + self.delete_evaluation_result: gapic_v1.method.wrap_method( + self.delete_evaluation_result, + default_timeout=None, + client_info=client_info, + ), + self.delete_evaluation_dataset: gapic_v1.method.wrap_method( + self.delete_evaluation_dataset, + default_timeout=None, + client_info=client_info, + ), + self.delete_evaluation_run: gapic_v1.method.wrap_method( + self.delete_evaluation_run, + default_timeout=None, + client_info=client_info, + ), + self.get_evaluation: gapic_v1.method.wrap_method( + self.get_evaluation, + default_timeout=None, + client_info=client_info, + ), + self.get_evaluation_result: gapic_v1.method.wrap_method( + self.get_evaluation_result, + default_timeout=None, + client_info=client_info, + ), + self.get_evaluation_dataset: gapic_v1.method.wrap_method( + self.get_evaluation_dataset, + default_timeout=None, + client_info=client_info, + ), + self.get_evaluation_run: gapic_v1.method.wrap_method( + self.get_evaluation_run, + default_timeout=None, + client_info=client_info, + ), + self.list_evaluations: gapic_v1.method.wrap_method( + self.list_evaluations, + default_timeout=None, + client_info=client_info, + ), + self.list_evaluation_results: gapic_v1.method.wrap_method( + self.list_evaluation_results, + default_timeout=None, + client_info=client_info, + ), + self.list_evaluation_datasets: gapic_v1.method.wrap_method( + self.list_evaluation_datasets, + default_timeout=None, + client_info=client_info, + ), + self.list_evaluation_runs: gapic_v1.method.wrap_method( + self.list_evaluation_runs, + default_timeout=None, + client_info=client_info, + ), + self.list_evaluation_expectations: gapic_v1.method.wrap_method( + self.list_evaluation_expectations, + default_timeout=None, + client_info=client_info, + ), + self.get_evaluation_expectation: gapic_v1.method.wrap_method( + self.get_evaluation_expectation, + default_timeout=None, + client_info=client_info, + ), + self.create_evaluation_expectation: gapic_v1.method.wrap_method( + self.create_evaluation_expectation, + default_timeout=None, + client_info=client_info, + ), + self.update_evaluation_expectation: gapic_v1.method.wrap_method( + self.update_evaluation_expectation, + default_timeout=None, + client_info=client_info, + ), + self.delete_evaluation_expectation: gapic_v1.method.wrap_method( + self.delete_evaluation_expectation, + default_timeout=None, + client_info=client_info, + ), + self.create_scheduled_evaluation_run: gapic_v1.method.wrap_method( + self.create_scheduled_evaluation_run, + default_timeout=None, + client_info=client_info, + ), + self.get_scheduled_evaluation_run: gapic_v1.method.wrap_method( + self.get_scheduled_evaluation_run, + default_timeout=None, + client_info=client_info, + ), + self.list_scheduled_evaluation_runs: gapic_v1.method.wrap_method( + self.list_scheduled_evaluation_runs, + default_timeout=None, + client_info=client_info, + ), + self.update_scheduled_evaluation_run: gapic_v1.method.wrap_method( + self.update_scheduled_evaluation_run, + default_timeout=None, + client_info=client_info, + ), + self.delete_scheduled_evaluation_run: gapic_v1.method.wrap_method( + self.delete_scheduled_evaluation_run, + default_timeout=None, + client_info=client_info, + ), + self.test_persona_voice: gapic_v1.method.wrap_method( + self.test_persona_voice, + default_timeout=None, + client_info=client_info, + ), + self.get_location: gapic_v1.method.wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: gapic_v1.method.wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def run_evaluation( + self, + ) -> Callable[ + [evaluation.RunEvaluationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def upload_evaluation_audio( + self, + ) -> Callable[ + [evaluation_service.UploadEvaluationAudioRequest], + Union[ + evaluation_service.UploadEvaluationAudioResponse, + Awaitable[evaluation_service.UploadEvaluationAudioResponse], + ], + ]: + raise NotImplementedError() + + @property + def create_evaluation( + self, + ) -> Callable[ + [evaluation_service.CreateEvaluationRequest], + Union[gcc_evaluation.Evaluation, Awaitable[gcc_evaluation.Evaluation]], + ]: + raise NotImplementedError() + + @property + def generate_evaluation( + self, + ) -> Callable[ + [evaluation_service.GenerateEvaluationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def import_evaluations( + self, + ) -> Callable[ + [evaluation_service.ImportEvaluationsRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def create_evaluation_dataset( + self, + ) -> Callable[ + [evaluation_service.CreateEvaluationDatasetRequest], + Union[evaluation.EvaluationDataset, Awaitable[evaluation.EvaluationDataset]], + ]: + raise NotImplementedError() + + @property + def update_evaluation( + self, + ) -> Callable[ + [evaluation_service.UpdateEvaluationRequest], + Union[gcc_evaluation.Evaluation, Awaitable[gcc_evaluation.Evaluation]], + ]: + raise NotImplementedError() + + @property + def update_evaluation_dataset( + self, + ) -> Callable[ + [evaluation_service.UpdateEvaluationDatasetRequest], + Union[evaluation.EvaluationDataset, Awaitable[evaluation.EvaluationDataset]], + ]: + raise NotImplementedError() + + @property + def delete_evaluation( + self, + ) -> Callable[ + [evaluation_service.DeleteEvaluationRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def delete_evaluation_result( + self, + ) -> Callable[ + [evaluation_service.DeleteEvaluationResultRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def delete_evaluation_dataset( + self, + ) -> Callable[ + [evaluation_service.DeleteEvaluationDatasetRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def delete_evaluation_run( + self, + ) -> Callable[ + [evaluation_service.DeleteEvaluationRunRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_evaluation( + self, + ) -> Callable[ + [evaluation_service.GetEvaluationRequest], + Union[evaluation.Evaluation, Awaitable[evaluation.Evaluation]], + ]: + raise NotImplementedError() + + @property + def get_evaluation_result( + self, + ) -> Callable[ + [evaluation_service.GetEvaluationResultRequest], + Union[evaluation.EvaluationResult, Awaitable[evaluation.EvaluationResult]], + ]: + raise NotImplementedError() + + @property + def get_evaluation_dataset( + self, + ) -> Callable[ + [evaluation_service.GetEvaluationDatasetRequest], + Union[evaluation.EvaluationDataset, Awaitable[evaluation.EvaluationDataset]], + ]: + raise NotImplementedError() + + @property + def get_evaluation_run( + self, + ) -> Callable[ + [evaluation_service.GetEvaluationRunRequest], + Union[evaluation.EvaluationRun, Awaitable[evaluation.EvaluationRun]], + ]: + raise NotImplementedError() + + @property + def list_evaluations( + self, + ) -> Callable[ + [evaluation_service.ListEvaluationsRequest], + Union[ + evaluation_service.ListEvaluationsResponse, + Awaitable[evaluation_service.ListEvaluationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_evaluation_results( + self, + ) -> Callable[ + [evaluation_service.ListEvaluationResultsRequest], + Union[ + evaluation_service.ListEvaluationResultsResponse, + Awaitable[evaluation_service.ListEvaluationResultsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_evaluation_datasets( + self, + ) -> Callable[ + [evaluation_service.ListEvaluationDatasetsRequest], + Union[ + evaluation_service.ListEvaluationDatasetsResponse, + Awaitable[evaluation_service.ListEvaluationDatasetsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_evaluation_runs( + self, + ) -> Callable[ + [evaluation_service.ListEvaluationRunsRequest], + Union[ + evaluation_service.ListEvaluationRunsResponse, + Awaitable[evaluation_service.ListEvaluationRunsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_evaluation_expectations( + self, + ) -> Callable[ + [evaluation_service.ListEvaluationExpectationsRequest], + Union[ + evaluation_service.ListEvaluationExpectationsResponse, + Awaitable[evaluation_service.ListEvaluationExpectationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_evaluation_expectation( + self, + ) -> Callable[ + [evaluation_service.GetEvaluationExpectationRequest], + Union[ + evaluation.EvaluationExpectation, + Awaitable[evaluation.EvaluationExpectation], + ], + ]: + raise NotImplementedError() + + @property + def create_evaluation_expectation( + self, + ) -> Callable[ + [evaluation_service.CreateEvaluationExpectationRequest], + Union[ + evaluation.EvaluationExpectation, + Awaitable[evaluation.EvaluationExpectation], + ], + ]: + raise NotImplementedError() + + @property + def update_evaluation_expectation( + self, + ) -> Callable[ + [evaluation_service.UpdateEvaluationExpectationRequest], + Union[ + evaluation.EvaluationExpectation, + Awaitable[evaluation.EvaluationExpectation], + ], + ]: + raise NotImplementedError() + + @property + def delete_evaluation_expectation( + self, + ) -> Callable[ + [evaluation_service.DeleteEvaluationExpectationRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def create_scheduled_evaluation_run( + self, + ) -> Callable[ + [evaluation_service.CreateScheduledEvaluationRunRequest], + Union[ + evaluation.ScheduledEvaluationRun, + Awaitable[evaluation.ScheduledEvaluationRun], + ], + ]: + raise NotImplementedError() + + @property + def get_scheduled_evaluation_run( + self, + ) -> Callable[ + [evaluation_service.GetScheduledEvaluationRunRequest], + Union[ + evaluation.ScheduledEvaluationRun, + Awaitable[evaluation.ScheduledEvaluationRun], + ], + ]: + raise NotImplementedError() + + @property + def list_scheduled_evaluation_runs( + self, + ) -> Callable[ + [evaluation_service.ListScheduledEvaluationRunsRequest], + Union[ + evaluation_service.ListScheduledEvaluationRunsResponse, + Awaitable[evaluation_service.ListScheduledEvaluationRunsResponse], + ], + ]: + raise NotImplementedError() + + @property + def update_scheduled_evaluation_run( + self, + ) -> Callable[ + [evaluation_service.UpdateScheduledEvaluationRunRequest], + Union[ + evaluation.ScheduledEvaluationRun, + Awaitable[evaluation.ScheduledEvaluationRun], + ], + ]: + raise NotImplementedError() + + @property + def delete_scheduled_evaluation_run( + self, + ) -> Callable[ + [evaluation_service.DeleteScheduledEvaluationRunRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def test_persona_voice( + self, + ) -> Callable[ + [evaluation_service.TestPersonaVoiceRequest], + Union[ + evaluation_service.TestPersonaVoiceResponse, + Awaitable[evaluation_service.TestPersonaVoiceResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def get_location( + self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[ + locations_pb2.ListLocationsResponse, + Awaitable[locations_pb2.ListLocationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("EvaluationServiceTransport",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/transports/grpc.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/transports/grpc.py new file mode 100644 index 000000000000..be7dc7e1b385 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/transports/grpc.py @@ -0,0 +1,1362 @@ +# -*- coding: utf-8 -*- +# 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. +# +import json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers, operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson + +from google.cloud.ces_v1beta.types import evaluation, evaluation_service +from google.cloud.ces_v1beta.types import evaluation as gcc_evaluation + +from .base import DEFAULT_CLIENT_INFO, EvaluationServiceTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class EvaluationServiceGrpcTransport(EvaluationServiceTransport): + """gRPC backend transport for EvaluationService. + + EvaluationService exposes methods to perform evaluation for + the CES app. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "ces.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'ces.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "ces.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def run_evaluation( + self, + ) -> Callable[[evaluation.RunEvaluationRequest], operations_pb2.Operation]: + r"""Return a callable for the run evaluation method over gRPC. + + Runs an evaluation of the app. + + Returns: + Callable[[~.RunEvaluationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "run_evaluation" not in self._stubs: + self._stubs["run_evaluation"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/RunEvaluation", + request_serializer=evaluation.RunEvaluationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["run_evaluation"] + + @property + def upload_evaluation_audio( + self, + ) -> Callable[ + [evaluation_service.UploadEvaluationAudioRequest], + evaluation_service.UploadEvaluationAudioResponse, + ]: + r"""Return a callable for the upload evaluation audio method over gRPC. + + Uploads audio for use in Golden Evaluations. Stores the audio in + the Cloud Storage bucket defined in + 'App.logging_settings.evaluation_audio_recording_config.gcs_bucket' + and returns a transcript. + + Returns: + Callable[[~.UploadEvaluationAudioRequest], + ~.UploadEvaluationAudioResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "upload_evaluation_audio" not in self._stubs: + self._stubs["upload_evaluation_audio"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/UploadEvaluationAudio", + request_serializer=evaluation_service.UploadEvaluationAudioRequest.serialize, + response_deserializer=evaluation_service.UploadEvaluationAudioResponse.deserialize, + ) + return self._stubs["upload_evaluation_audio"] + + @property + def create_evaluation( + self, + ) -> Callable[ + [evaluation_service.CreateEvaluationRequest], gcc_evaluation.Evaluation + ]: + r"""Return a callable for the create evaluation method over gRPC. + + Creates an evaluation. + + Returns: + Callable[[~.CreateEvaluationRequest], + ~.Evaluation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_evaluation" not in self._stubs: + self._stubs["create_evaluation"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/CreateEvaluation", + request_serializer=evaluation_service.CreateEvaluationRequest.serialize, + response_deserializer=gcc_evaluation.Evaluation.deserialize, + ) + return self._stubs["create_evaluation"] + + @property + def generate_evaluation( + self, + ) -> Callable[ + [evaluation_service.GenerateEvaluationRequest], operations_pb2.Operation + ]: + r"""Return a callable for the generate evaluation method over gRPC. + + Creates a golden evaluation from a conversation. + + Returns: + Callable[[~.GenerateEvaluationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "generate_evaluation" not in self._stubs: + self._stubs["generate_evaluation"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/GenerateEvaluation", + request_serializer=evaluation_service.GenerateEvaluationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["generate_evaluation"] + + @property + def import_evaluations( + self, + ) -> Callable[ + [evaluation_service.ImportEvaluationsRequest], operations_pb2.Operation + ]: + r"""Return a callable for the import evaluations method over gRPC. + + Imports evaluations into the app. + + Returns: + Callable[[~.ImportEvaluationsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "import_evaluations" not in self._stubs: + self._stubs["import_evaluations"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/ImportEvaluations", + request_serializer=evaluation_service.ImportEvaluationsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["import_evaluations"] + + @property + def create_evaluation_dataset( + self, + ) -> Callable[ + [evaluation_service.CreateEvaluationDatasetRequest], + evaluation.EvaluationDataset, + ]: + r"""Return a callable for the create evaluation dataset method over gRPC. + + Creates an evaluation dataset. + + Returns: + Callable[[~.CreateEvaluationDatasetRequest], + ~.EvaluationDataset]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_evaluation_dataset" not in self._stubs: + self._stubs["create_evaluation_dataset"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/CreateEvaluationDataset", + request_serializer=evaluation_service.CreateEvaluationDatasetRequest.serialize, + response_deserializer=evaluation.EvaluationDataset.deserialize, + ) + return self._stubs["create_evaluation_dataset"] + + @property + def update_evaluation( + self, + ) -> Callable[ + [evaluation_service.UpdateEvaluationRequest], gcc_evaluation.Evaluation + ]: + r"""Return a callable for the update evaluation method over gRPC. + + Updates an evaluation. + + Returns: + Callable[[~.UpdateEvaluationRequest], + ~.Evaluation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_evaluation" not in self._stubs: + self._stubs["update_evaluation"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/UpdateEvaluation", + request_serializer=evaluation_service.UpdateEvaluationRequest.serialize, + response_deserializer=gcc_evaluation.Evaluation.deserialize, + ) + return self._stubs["update_evaluation"] + + @property + def update_evaluation_dataset( + self, + ) -> Callable[ + [evaluation_service.UpdateEvaluationDatasetRequest], + evaluation.EvaluationDataset, + ]: + r"""Return a callable for the update evaluation dataset method over gRPC. + + Updates an evaluation dataset. + + Returns: + Callable[[~.UpdateEvaluationDatasetRequest], + ~.EvaluationDataset]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_evaluation_dataset" not in self._stubs: + self._stubs["update_evaluation_dataset"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/UpdateEvaluationDataset", + request_serializer=evaluation_service.UpdateEvaluationDatasetRequest.serialize, + response_deserializer=evaluation.EvaluationDataset.deserialize, + ) + return self._stubs["update_evaluation_dataset"] + + @property + def delete_evaluation( + self, + ) -> Callable[[evaluation_service.DeleteEvaluationRequest], empty_pb2.Empty]: + r"""Return a callable for the delete evaluation method over gRPC. + + Deletes an evaluation. + + Returns: + Callable[[~.DeleteEvaluationRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_evaluation" not in self._stubs: + self._stubs["delete_evaluation"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/DeleteEvaluation", + request_serializer=evaluation_service.DeleteEvaluationRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_evaluation"] + + @property + def delete_evaluation_result( + self, + ) -> Callable[[evaluation_service.DeleteEvaluationResultRequest], empty_pb2.Empty]: + r"""Return a callable for the delete evaluation result method over gRPC. + + Deletes an evaluation result. + + Returns: + Callable[[~.DeleteEvaluationResultRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_evaluation_result" not in self._stubs: + self._stubs["delete_evaluation_result"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/DeleteEvaluationResult", + request_serializer=evaluation_service.DeleteEvaluationResultRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_evaluation_result"] + + @property + def delete_evaluation_dataset( + self, + ) -> Callable[[evaluation_service.DeleteEvaluationDatasetRequest], empty_pb2.Empty]: + r"""Return a callable for the delete evaluation dataset method over gRPC. + + Deletes an evaluation dataset. + + Returns: + Callable[[~.DeleteEvaluationDatasetRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_evaluation_dataset" not in self._stubs: + self._stubs["delete_evaluation_dataset"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/DeleteEvaluationDataset", + request_serializer=evaluation_service.DeleteEvaluationDatasetRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_evaluation_dataset"] + + @property + def delete_evaluation_run( + self, + ) -> Callable[ + [evaluation_service.DeleteEvaluationRunRequest], operations_pb2.Operation + ]: + r"""Return a callable for the delete evaluation run method over gRPC. + + Deletes an evaluation run. + + Returns: + Callable[[~.DeleteEvaluationRunRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_evaluation_run" not in self._stubs: + self._stubs["delete_evaluation_run"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/DeleteEvaluationRun", + request_serializer=evaluation_service.DeleteEvaluationRunRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_evaluation_run"] + + @property + def get_evaluation( + self, + ) -> Callable[[evaluation_service.GetEvaluationRequest], evaluation.Evaluation]: + r"""Return a callable for the get evaluation method over gRPC. + + Gets details of the specified evaluation. + + Returns: + Callable[[~.GetEvaluationRequest], + ~.Evaluation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_evaluation" not in self._stubs: + self._stubs["get_evaluation"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/GetEvaluation", + request_serializer=evaluation_service.GetEvaluationRequest.serialize, + response_deserializer=evaluation.Evaluation.deserialize, + ) + return self._stubs["get_evaluation"] + + @property + def get_evaluation_result( + self, + ) -> Callable[ + [evaluation_service.GetEvaluationResultRequest], evaluation.EvaluationResult + ]: + r"""Return a callable for the get evaluation result method over gRPC. + + Gets details of the specified evaluation result. + + Returns: + Callable[[~.GetEvaluationResultRequest], + ~.EvaluationResult]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_evaluation_result" not in self._stubs: + self._stubs["get_evaluation_result"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/GetEvaluationResult", + request_serializer=evaluation_service.GetEvaluationResultRequest.serialize, + response_deserializer=evaluation.EvaluationResult.deserialize, + ) + return self._stubs["get_evaluation_result"] + + @property + def get_evaluation_dataset( + self, + ) -> Callable[ + [evaluation_service.GetEvaluationDatasetRequest], evaluation.EvaluationDataset + ]: + r"""Return a callable for the get evaluation dataset method over gRPC. + + Gets details of the specified evaluation dataset. + + Returns: + Callable[[~.GetEvaluationDatasetRequest], + ~.EvaluationDataset]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_evaluation_dataset" not in self._stubs: + self._stubs["get_evaluation_dataset"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/GetEvaluationDataset", + request_serializer=evaluation_service.GetEvaluationDatasetRequest.serialize, + response_deserializer=evaluation.EvaluationDataset.deserialize, + ) + return self._stubs["get_evaluation_dataset"] + + @property + def get_evaluation_run( + self, + ) -> Callable[ + [evaluation_service.GetEvaluationRunRequest], evaluation.EvaluationRun + ]: + r"""Return a callable for the get evaluation run method over gRPC. + + Gets details of the specified evaluation run. + + Returns: + Callable[[~.GetEvaluationRunRequest], + ~.EvaluationRun]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_evaluation_run" not in self._stubs: + self._stubs["get_evaluation_run"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/GetEvaluationRun", + request_serializer=evaluation_service.GetEvaluationRunRequest.serialize, + response_deserializer=evaluation.EvaluationRun.deserialize, + ) + return self._stubs["get_evaluation_run"] + + @property + def list_evaluations( + self, + ) -> Callable[ + [evaluation_service.ListEvaluationsRequest], + evaluation_service.ListEvaluationsResponse, + ]: + r"""Return a callable for the list evaluations method over gRPC. + + Lists all evaluations in the given app. + + Returns: + Callable[[~.ListEvaluationsRequest], + ~.ListEvaluationsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_evaluations" not in self._stubs: + self._stubs["list_evaluations"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/ListEvaluations", + request_serializer=evaluation_service.ListEvaluationsRequest.serialize, + response_deserializer=evaluation_service.ListEvaluationsResponse.deserialize, + ) + return self._stubs["list_evaluations"] + + @property + def list_evaluation_results( + self, + ) -> Callable[ + [evaluation_service.ListEvaluationResultsRequest], + evaluation_service.ListEvaluationResultsResponse, + ]: + r"""Return a callable for the list evaluation results method over gRPC. + + Lists all evaluation results for a given evaluation. + + Returns: + Callable[[~.ListEvaluationResultsRequest], + ~.ListEvaluationResultsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_evaluation_results" not in self._stubs: + self._stubs["list_evaluation_results"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/ListEvaluationResults", + request_serializer=evaluation_service.ListEvaluationResultsRequest.serialize, + response_deserializer=evaluation_service.ListEvaluationResultsResponse.deserialize, + ) + return self._stubs["list_evaluation_results"] + + @property + def list_evaluation_datasets( + self, + ) -> Callable[ + [evaluation_service.ListEvaluationDatasetsRequest], + evaluation_service.ListEvaluationDatasetsResponse, + ]: + r"""Return a callable for the list evaluation datasets method over gRPC. + + Lists all evaluation datasets in the given app. + + Returns: + Callable[[~.ListEvaluationDatasetsRequest], + ~.ListEvaluationDatasetsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_evaluation_datasets" not in self._stubs: + self._stubs["list_evaluation_datasets"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/ListEvaluationDatasets", + request_serializer=evaluation_service.ListEvaluationDatasetsRequest.serialize, + response_deserializer=evaluation_service.ListEvaluationDatasetsResponse.deserialize, + ) + return self._stubs["list_evaluation_datasets"] + + @property + def list_evaluation_runs( + self, + ) -> Callable[ + [evaluation_service.ListEvaluationRunsRequest], + evaluation_service.ListEvaluationRunsResponse, + ]: + r"""Return a callable for the list evaluation runs method over gRPC. + + Lists all evaluation runs in the given app. + + Returns: + Callable[[~.ListEvaluationRunsRequest], + ~.ListEvaluationRunsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_evaluation_runs" not in self._stubs: + self._stubs["list_evaluation_runs"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/ListEvaluationRuns", + request_serializer=evaluation_service.ListEvaluationRunsRequest.serialize, + response_deserializer=evaluation_service.ListEvaluationRunsResponse.deserialize, + ) + return self._stubs["list_evaluation_runs"] + + @property + def list_evaluation_expectations( + self, + ) -> Callable[ + [evaluation_service.ListEvaluationExpectationsRequest], + evaluation_service.ListEvaluationExpectationsResponse, + ]: + r"""Return a callable for the list evaluation expectations method over gRPC. + + Lists all evaluation expectations in the given app. + + Returns: + Callable[[~.ListEvaluationExpectationsRequest], + ~.ListEvaluationExpectationsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_evaluation_expectations" not in self._stubs: + self._stubs["list_evaluation_expectations"] = ( + self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/ListEvaluationExpectations", + request_serializer=evaluation_service.ListEvaluationExpectationsRequest.serialize, + response_deserializer=evaluation_service.ListEvaluationExpectationsResponse.deserialize, + ) + ) + return self._stubs["list_evaluation_expectations"] + + @property + def get_evaluation_expectation( + self, + ) -> Callable[ + [evaluation_service.GetEvaluationExpectationRequest], + evaluation.EvaluationExpectation, + ]: + r"""Return a callable for the get evaluation expectation method over gRPC. + + Gets details of the specified evaluation expectation. + + Returns: + Callable[[~.GetEvaluationExpectationRequest], + ~.EvaluationExpectation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_evaluation_expectation" not in self._stubs: + self._stubs["get_evaluation_expectation"] = ( + self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/GetEvaluationExpectation", + request_serializer=evaluation_service.GetEvaluationExpectationRequest.serialize, + response_deserializer=evaluation.EvaluationExpectation.deserialize, + ) + ) + return self._stubs["get_evaluation_expectation"] + + @property + def create_evaluation_expectation( + self, + ) -> Callable[ + [evaluation_service.CreateEvaluationExpectationRequest], + evaluation.EvaluationExpectation, + ]: + r"""Return a callable for the create evaluation expectation method over gRPC. + + Creates an evaluation expectation. + + Returns: + Callable[[~.CreateEvaluationExpectationRequest], + ~.EvaluationExpectation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_evaluation_expectation" not in self._stubs: + self._stubs["create_evaluation_expectation"] = ( + self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/CreateEvaluationExpectation", + request_serializer=evaluation_service.CreateEvaluationExpectationRequest.serialize, + response_deserializer=evaluation.EvaluationExpectation.deserialize, + ) + ) + return self._stubs["create_evaluation_expectation"] + + @property + def update_evaluation_expectation( + self, + ) -> Callable[ + [evaluation_service.UpdateEvaluationExpectationRequest], + evaluation.EvaluationExpectation, + ]: + r"""Return a callable for the update evaluation expectation method over gRPC. + + Updates an evaluation expectation. + + Returns: + Callable[[~.UpdateEvaluationExpectationRequest], + ~.EvaluationExpectation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_evaluation_expectation" not in self._stubs: + self._stubs["update_evaluation_expectation"] = ( + self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/UpdateEvaluationExpectation", + request_serializer=evaluation_service.UpdateEvaluationExpectationRequest.serialize, + response_deserializer=evaluation.EvaluationExpectation.deserialize, + ) + ) + return self._stubs["update_evaluation_expectation"] + + @property + def delete_evaluation_expectation( + self, + ) -> Callable[ + [evaluation_service.DeleteEvaluationExpectationRequest], empty_pb2.Empty + ]: + r"""Return a callable for the delete evaluation expectation method over gRPC. + + Deletes an evaluation expectation. + + Returns: + Callable[[~.DeleteEvaluationExpectationRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_evaluation_expectation" not in self._stubs: + self._stubs["delete_evaluation_expectation"] = ( + self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/DeleteEvaluationExpectation", + request_serializer=evaluation_service.DeleteEvaluationExpectationRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + ) + return self._stubs["delete_evaluation_expectation"] + + @property + def create_scheduled_evaluation_run( + self, + ) -> Callable[ + [evaluation_service.CreateScheduledEvaluationRunRequest], + evaluation.ScheduledEvaluationRun, + ]: + r"""Return a callable for the create scheduled evaluation + run method over gRPC. + + Creates a scheduled evaluation run. + + Returns: + Callable[[~.CreateScheduledEvaluationRunRequest], + ~.ScheduledEvaluationRun]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_scheduled_evaluation_run" not in self._stubs: + self._stubs["create_scheduled_evaluation_run"] = ( + self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/CreateScheduledEvaluationRun", + request_serializer=evaluation_service.CreateScheduledEvaluationRunRequest.serialize, + response_deserializer=evaluation.ScheduledEvaluationRun.deserialize, + ) + ) + return self._stubs["create_scheduled_evaluation_run"] + + @property + def get_scheduled_evaluation_run( + self, + ) -> Callable[ + [evaluation_service.GetScheduledEvaluationRunRequest], + evaluation.ScheduledEvaluationRun, + ]: + r"""Return a callable for the get scheduled evaluation run method over gRPC. + + Gets details of the specified scheduled evaluation + run. + + Returns: + Callable[[~.GetScheduledEvaluationRunRequest], + ~.ScheduledEvaluationRun]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_scheduled_evaluation_run" not in self._stubs: + self._stubs["get_scheduled_evaluation_run"] = ( + self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/GetScheduledEvaluationRun", + request_serializer=evaluation_service.GetScheduledEvaluationRunRequest.serialize, + response_deserializer=evaluation.ScheduledEvaluationRun.deserialize, + ) + ) + return self._stubs["get_scheduled_evaluation_run"] + + @property + def list_scheduled_evaluation_runs( + self, + ) -> Callable[ + [evaluation_service.ListScheduledEvaluationRunsRequest], + evaluation_service.ListScheduledEvaluationRunsResponse, + ]: + r"""Return a callable for the list scheduled evaluation runs method over gRPC. + + Lists all scheduled evaluation runs in the given app. + + Returns: + Callable[[~.ListScheduledEvaluationRunsRequest], + ~.ListScheduledEvaluationRunsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_scheduled_evaluation_runs" not in self._stubs: + self._stubs["list_scheduled_evaluation_runs"] = ( + self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/ListScheduledEvaluationRuns", + request_serializer=evaluation_service.ListScheduledEvaluationRunsRequest.serialize, + response_deserializer=evaluation_service.ListScheduledEvaluationRunsResponse.deserialize, + ) + ) + return self._stubs["list_scheduled_evaluation_runs"] + + @property + def update_scheduled_evaluation_run( + self, + ) -> Callable[ + [evaluation_service.UpdateScheduledEvaluationRunRequest], + evaluation.ScheduledEvaluationRun, + ]: + r"""Return a callable for the update scheduled evaluation + run method over gRPC. + + Updates a scheduled evaluation run. + + Returns: + Callable[[~.UpdateScheduledEvaluationRunRequest], + ~.ScheduledEvaluationRun]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_scheduled_evaluation_run" not in self._stubs: + self._stubs["update_scheduled_evaluation_run"] = ( + self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/UpdateScheduledEvaluationRun", + request_serializer=evaluation_service.UpdateScheduledEvaluationRunRequest.serialize, + response_deserializer=evaluation.ScheduledEvaluationRun.deserialize, + ) + ) + return self._stubs["update_scheduled_evaluation_run"] + + @property + def delete_scheduled_evaluation_run( + self, + ) -> Callable[ + [evaluation_service.DeleteScheduledEvaluationRunRequest], empty_pb2.Empty + ]: + r"""Return a callable for the delete scheduled evaluation + run method over gRPC. + + Deletes a scheduled evaluation run. + + Returns: + Callable[[~.DeleteScheduledEvaluationRunRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_scheduled_evaluation_run" not in self._stubs: + self._stubs["delete_scheduled_evaluation_run"] = ( + self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/DeleteScheduledEvaluationRun", + request_serializer=evaluation_service.DeleteScheduledEvaluationRunRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + ) + return self._stubs["delete_scheduled_evaluation_run"] + + @property + def test_persona_voice( + self, + ) -> Callable[ + [evaluation_service.TestPersonaVoiceRequest], + evaluation_service.TestPersonaVoiceResponse, + ]: + r"""Return a callable for the test persona voice method over gRPC. + + Tests the voice of a persona. Also accepts a default + persona. + + Returns: + Callable[[~.TestPersonaVoiceRequest], + ~.TestPersonaVoiceResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_persona_voice" not in self._stubs: + self._stubs["test_persona_voice"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/TestPersonaVoice", + request_serializer=evaluation_service.TestPersonaVoiceRequest.serialize, + response_deserializer=evaluation_service.TestPersonaVoiceResponse.deserialize, + ) + return self._stubs["test_persona_voice"] + + def close(self): + self._logged_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("EvaluationServiceGrpcTransport",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/transports/grpc_asyncio.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..dd228d6c6380 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/transports/grpc_asyncio.py @@ -0,0 +1,1585 @@ +# -*- coding: utf-8 -*- +# 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. +# +import inspect +import json +import logging as std_logging +import pickle +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +from grpc.experimental import aio # type: ignore + +from google.cloud.ces_v1beta.types import evaluation, evaluation_service +from google.cloud.ces_v1beta.types import evaluation as gcc_evaluation + +from .base import DEFAULT_CLIENT_INFO, EvaluationServiceTransport +from .grpc import EvaluationServiceGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class EvaluationServiceGrpcAsyncIOTransport(EvaluationServiceTransport): + """gRPC AsyncIO backend transport for EvaluationService. + + EvaluationService exposes methods to perform evaluation for + the CES app. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "ces.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "ces.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'ces.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self._logged_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def run_evaluation( + self, + ) -> Callable[ + [evaluation.RunEvaluationRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the run evaluation method over gRPC. + + Runs an evaluation of the app. + + Returns: + Callable[[~.RunEvaluationRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "run_evaluation" not in self._stubs: + self._stubs["run_evaluation"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/RunEvaluation", + request_serializer=evaluation.RunEvaluationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["run_evaluation"] + + @property + def upload_evaluation_audio( + self, + ) -> Callable[ + [evaluation_service.UploadEvaluationAudioRequest], + Awaitable[evaluation_service.UploadEvaluationAudioResponse], + ]: + r"""Return a callable for the upload evaluation audio method over gRPC. + + Uploads audio for use in Golden Evaluations. Stores the audio in + the Cloud Storage bucket defined in + 'App.logging_settings.evaluation_audio_recording_config.gcs_bucket' + and returns a transcript. + + Returns: + Callable[[~.UploadEvaluationAudioRequest], + Awaitable[~.UploadEvaluationAudioResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "upload_evaluation_audio" not in self._stubs: + self._stubs["upload_evaluation_audio"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/UploadEvaluationAudio", + request_serializer=evaluation_service.UploadEvaluationAudioRequest.serialize, + response_deserializer=evaluation_service.UploadEvaluationAudioResponse.deserialize, + ) + return self._stubs["upload_evaluation_audio"] + + @property + def create_evaluation( + self, + ) -> Callable[ + [evaluation_service.CreateEvaluationRequest], + Awaitable[gcc_evaluation.Evaluation], + ]: + r"""Return a callable for the create evaluation method over gRPC. + + Creates an evaluation. + + Returns: + Callable[[~.CreateEvaluationRequest], + Awaitable[~.Evaluation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_evaluation" not in self._stubs: + self._stubs["create_evaluation"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/CreateEvaluation", + request_serializer=evaluation_service.CreateEvaluationRequest.serialize, + response_deserializer=gcc_evaluation.Evaluation.deserialize, + ) + return self._stubs["create_evaluation"] + + @property + def generate_evaluation( + self, + ) -> Callable[ + [evaluation_service.GenerateEvaluationRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the generate evaluation method over gRPC. + + Creates a golden evaluation from a conversation. + + Returns: + Callable[[~.GenerateEvaluationRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "generate_evaluation" not in self._stubs: + self._stubs["generate_evaluation"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/GenerateEvaluation", + request_serializer=evaluation_service.GenerateEvaluationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["generate_evaluation"] + + @property + def import_evaluations( + self, + ) -> Callable[ + [evaluation_service.ImportEvaluationsRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the import evaluations method over gRPC. + + Imports evaluations into the app. + + Returns: + Callable[[~.ImportEvaluationsRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "import_evaluations" not in self._stubs: + self._stubs["import_evaluations"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/ImportEvaluations", + request_serializer=evaluation_service.ImportEvaluationsRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["import_evaluations"] + + @property + def create_evaluation_dataset( + self, + ) -> Callable[ + [evaluation_service.CreateEvaluationDatasetRequest], + Awaitable[evaluation.EvaluationDataset], + ]: + r"""Return a callable for the create evaluation dataset method over gRPC. + + Creates an evaluation dataset. + + Returns: + Callable[[~.CreateEvaluationDatasetRequest], + Awaitable[~.EvaluationDataset]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_evaluation_dataset" not in self._stubs: + self._stubs["create_evaluation_dataset"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/CreateEvaluationDataset", + request_serializer=evaluation_service.CreateEvaluationDatasetRequest.serialize, + response_deserializer=evaluation.EvaluationDataset.deserialize, + ) + return self._stubs["create_evaluation_dataset"] + + @property + def update_evaluation( + self, + ) -> Callable[ + [evaluation_service.UpdateEvaluationRequest], + Awaitable[gcc_evaluation.Evaluation], + ]: + r"""Return a callable for the update evaluation method over gRPC. + + Updates an evaluation. + + Returns: + Callable[[~.UpdateEvaluationRequest], + Awaitable[~.Evaluation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_evaluation" not in self._stubs: + self._stubs["update_evaluation"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/UpdateEvaluation", + request_serializer=evaluation_service.UpdateEvaluationRequest.serialize, + response_deserializer=gcc_evaluation.Evaluation.deserialize, + ) + return self._stubs["update_evaluation"] + + @property + def update_evaluation_dataset( + self, + ) -> Callable[ + [evaluation_service.UpdateEvaluationDatasetRequest], + Awaitable[evaluation.EvaluationDataset], + ]: + r"""Return a callable for the update evaluation dataset method over gRPC. + + Updates an evaluation dataset. + + Returns: + Callable[[~.UpdateEvaluationDatasetRequest], + Awaitable[~.EvaluationDataset]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_evaluation_dataset" not in self._stubs: + self._stubs["update_evaluation_dataset"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/UpdateEvaluationDataset", + request_serializer=evaluation_service.UpdateEvaluationDatasetRequest.serialize, + response_deserializer=evaluation.EvaluationDataset.deserialize, + ) + return self._stubs["update_evaluation_dataset"] + + @property + def delete_evaluation( + self, + ) -> Callable[ + [evaluation_service.DeleteEvaluationRequest], Awaitable[empty_pb2.Empty] + ]: + r"""Return a callable for the delete evaluation method over gRPC. + + Deletes an evaluation. + + Returns: + Callable[[~.DeleteEvaluationRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_evaluation" not in self._stubs: + self._stubs["delete_evaluation"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/DeleteEvaluation", + request_serializer=evaluation_service.DeleteEvaluationRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_evaluation"] + + @property + def delete_evaluation_result( + self, + ) -> Callable[ + [evaluation_service.DeleteEvaluationResultRequest], Awaitable[empty_pb2.Empty] + ]: + r"""Return a callable for the delete evaluation result method over gRPC. + + Deletes an evaluation result. + + Returns: + Callable[[~.DeleteEvaluationResultRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_evaluation_result" not in self._stubs: + self._stubs["delete_evaluation_result"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/DeleteEvaluationResult", + request_serializer=evaluation_service.DeleteEvaluationResultRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_evaluation_result"] + + @property + def delete_evaluation_dataset( + self, + ) -> Callable[ + [evaluation_service.DeleteEvaluationDatasetRequest], Awaitable[empty_pb2.Empty] + ]: + r"""Return a callable for the delete evaluation dataset method over gRPC. + + Deletes an evaluation dataset. + + Returns: + Callable[[~.DeleteEvaluationDatasetRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_evaluation_dataset" not in self._stubs: + self._stubs["delete_evaluation_dataset"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/DeleteEvaluationDataset", + request_serializer=evaluation_service.DeleteEvaluationDatasetRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_evaluation_dataset"] + + @property + def delete_evaluation_run( + self, + ) -> Callable[ + [evaluation_service.DeleteEvaluationRunRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the delete evaluation run method over gRPC. + + Deletes an evaluation run. + + Returns: + Callable[[~.DeleteEvaluationRunRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_evaluation_run" not in self._stubs: + self._stubs["delete_evaluation_run"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/DeleteEvaluationRun", + request_serializer=evaluation_service.DeleteEvaluationRunRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_evaluation_run"] + + @property + def get_evaluation( + self, + ) -> Callable[ + [evaluation_service.GetEvaluationRequest], Awaitable[evaluation.Evaluation] + ]: + r"""Return a callable for the get evaluation method over gRPC. + + Gets details of the specified evaluation. + + Returns: + Callable[[~.GetEvaluationRequest], + Awaitable[~.Evaluation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_evaluation" not in self._stubs: + self._stubs["get_evaluation"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/GetEvaluation", + request_serializer=evaluation_service.GetEvaluationRequest.serialize, + response_deserializer=evaluation.Evaluation.deserialize, + ) + return self._stubs["get_evaluation"] + + @property + def get_evaluation_result( + self, + ) -> Callable[ + [evaluation_service.GetEvaluationResultRequest], + Awaitable[evaluation.EvaluationResult], + ]: + r"""Return a callable for the get evaluation result method over gRPC. + + Gets details of the specified evaluation result. + + Returns: + Callable[[~.GetEvaluationResultRequest], + Awaitable[~.EvaluationResult]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_evaluation_result" not in self._stubs: + self._stubs["get_evaluation_result"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/GetEvaluationResult", + request_serializer=evaluation_service.GetEvaluationResultRequest.serialize, + response_deserializer=evaluation.EvaluationResult.deserialize, + ) + return self._stubs["get_evaluation_result"] + + @property + def get_evaluation_dataset( + self, + ) -> Callable[ + [evaluation_service.GetEvaluationDatasetRequest], + Awaitable[evaluation.EvaluationDataset], + ]: + r"""Return a callable for the get evaluation dataset method over gRPC. + + Gets details of the specified evaluation dataset. + + Returns: + Callable[[~.GetEvaluationDatasetRequest], + Awaitable[~.EvaluationDataset]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_evaluation_dataset" not in self._stubs: + self._stubs["get_evaluation_dataset"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/GetEvaluationDataset", + request_serializer=evaluation_service.GetEvaluationDatasetRequest.serialize, + response_deserializer=evaluation.EvaluationDataset.deserialize, + ) + return self._stubs["get_evaluation_dataset"] + + @property + def get_evaluation_run( + self, + ) -> Callable[ + [evaluation_service.GetEvaluationRunRequest], + Awaitable[evaluation.EvaluationRun], + ]: + r"""Return a callable for the get evaluation run method over gRPC. + + Gets details of the specified evaluation run. + + Returns: + Callable[[~.GetEvaluationRunRequest], + Awaitable[~.EvaluationRun]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_evaluation_run" not in self._stubs: + self._stubs["get_evaluation_run"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/GetEvaluationRun", + request_serializer=evaluation_service.GetEvaluationRunRequest.serialize, + response_deserializer=evaluation.EvaluationRun.deserialize, + ) + return self._stubs["get_evaluation_run"] + + @property + def list_evaluations( + self, + ) -> Callable[ + [evaluation_service.ListEvaluationsRequest], + Awaitable[evaluation_service.ListEvaluationsResponse], + ]: + r"""Return a callable for the list evaluations method over gRPC. + + Lists all evaluations in the given app. + + Returns: + Callable[[~.ListEvaluationsRequest], + Awaitable[~.ListEvaluationsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_evaluations" not in self._stubs: + self._stubs["list_evaluations"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/ListEvaluations", + request_serializer=evaluation_service.ListEvaluationsRequest.serialize, + response_deserializer=evaluation_service.ListEvaluationsResponse.deserialize, + ) + return self._stubs["list_evaluations"] + + @property + def list_evaluation_results( + self, + ) -> Callable[ + [evaluation_service.ListEvaluationResultsRequest], + Awaitable[evaluation_service.ListEvaluationResultsResponse], + ]: + r"""Return a callable for the list evaluation results method over gRPC. + + Lists all evaluation results for a given evaluation. + + Returns: + Callable[[~.ListEvaluationResultsRequest], + Awaitable[~.ListEvaluationResultsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_evaluation_results" not in self._stubs: + self._stubs["list_evaluation_results"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/ListEvaluationResults", + request_serializer=evaluation_service.ListEvaluationResultsRequest.serialize, + response_deserializer=evaluation_service.ListEvaluationResultsResponse.deserialize, + ) + return self._stubs["list_evaluation_results"] + + @property + def list_evaluation_datasets( + self, + ) -> Callable[ + [evaluation_service.ListEvaluationDatasetsRequest], + Awaitable[evaluation_service.ListEvaluationDatasetsResponse], + ]: + r"""Return a callable for the list evaluation datasets method over gRPC. + + Lists all evaluation datasets in the given app. + + Returns: + Callable[[~.ListEvaluationDatasetsRequest], + Awaitable[~.ListEvaluationDatasetsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_evaluation_datasets" not in self._stubs: + self._stubs["list_evaluation_datasets"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/ListEvaluationDatasets", + request_serializer=evaluation_service.ListEvaluationDatasetsRequest.serialize, + response_deserializer=evaluation_service.ListEvaluationDatasetsResponse.deserialize, + ) + return self._stubs["list_evaluation_datasets"] + + @property + def list_evaluation_runs( + self, + ) -> Callable[ + [evaluation_service.ListEvaluationRunsRequest], + Awaitable[evaluation_service.ListEvaluationRunsResponse], + ]: + r"""Return a callable for the list evaluation runs method over gRPC. + + Lists all evaluation runs in the given app. + + Returns: + Callable[[~.ListEvaluationRunsRequest], + Awaitable[~.ListEvaluationRunsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_evaluation_runs" not in self._stubs: + self._stubs["list_evaluation_runs"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/ListEvaluationRuns", + request_serializer=evaluation_service.ListEvaluationRunsRequest.serialize, + response_deserializer=evaluation_service.ListEvaluationRunsResponse.deserialize, + ) + return self._stubs["list_evaluation_runs"] + + @property + def list_evaluation_expectations( + self, + ) -> Callable[ + [evaluation_service.ListEvaluationExpectationsRequest], + Awaitable[evaluation_service.ListEvaluationExpectationsResponse], + ]: + r"""Return a callable for the list evaluation expectations method over gRPC. + + Lists all evaluation expectations in the given app. + + Returns: + Callable[[~.ListEvaluationExpectationsRequest], + Awaitable[~.ListEvaluationExpectationsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_evaluation_expectations" not in self._stubs: + self._stubs["list_evaluation_expectations"] = ( + self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/ListEvaluationExpectations", + request_serializer=evaluation_service.ListEvaluationExpectationsRequest.serialize, + response_deserializer=evaluation_service.ListEvaluationExpectationsResponse.deserialize, + ) + ) + return self._stubs["list_evaluation_expectations"] + + @property + def get_evaluation_expectation( + self, + ) -> Callable[ + [evaluation_service.GetEvaluationExpectationRequest], + Awaitable[evaluation.EvaluationExpectation], + ]: + r"""Return a callable for the get evaluation expectation method over gRPC. + + Gets details of the specified evaluation expectation. + + Returns: + Callable[[~.GetEvaluationExpectationRequest], + Awaitable[~.EvaluationExpectation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_evaluation_expectation" not in self._stubs: + self._stubs["get_evaluation_expectation"] = ( + self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/GetEvaluationExpectation", + request_serializer=evaluation_service.GetEvaluationExpectationRequest.serialize, + response_deserializer=evaluation.EvaluationExpectation.deserialize, + ) + ) + return self._stubs["get_evaluation_expectation"] + + @property + def create_evaluation_expectation( + self, + ) -> Callable[ + [evaluation_service.CreateEvaluationExpectationRequest], + Awaitable[evaluation.EvaluationExpectation], + ]: + r"""Return a callable for the create evaluation expectation method over gRPC. + + Creates an evaluation expectation. + + Returns: + Callable[[~.CreateEvaluationExpectationRequest], + Awaitable[~.EvaluationExpectation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_evaluation_expectation" not in self._stubs: + self._stubs["create_evaluation_expectation"] = ( + self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/CreateEvaluationExpectation", + request_serializer=evaluation_service.CreateEvaluationExpectationRequest.serialize, + response_deserializer=evaluation.EvaluationExpectation.deserialize, + ) + ) + return self._stubs["create_evaluation_expectation"] + + @property + def update_evaluation_expectation( + self, + ) -> Callable[ + [evaluation_service.UpdateEvaluationExpectationRequest], + Awaitable[evaluation.EvaluationExpectation], + ]: + r"""Return a callable for the update evaluation expectation method over gRPC. + + Updates an evaluation expectation. + + Returns: + Callable[[~.UpdateEvaluationExpectationRequest], + Awaitable[~.EvaluationExpectation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_evaluation_expectation" not in self._stubs: + self._stubs["update_evaluation_expectation"] = ( + self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/UpdateEvaluationExpectation", + request_serializer=evaluation_service.UpdateEvaluationExpectationRequest.serialize, + response_deserializer=evaluation.EvaluationExpectation.deserialize, + ) + ) + return self._stubs["update_evaluation_expectation"] + + @property + def delete_evaluation_expectation( + self, + ) -> Callable[ + [evaluation_service.DeleteEvaluationExpectationRequest], + Awaitable[empty_pb2.Empty], + ]: + r"""Return a callable for the delete evaluation expectation method over gRPC. + + Deletes an evaluation expectation. + + Returns: + Callable[[~.DeleteEvaluationExpectationRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_evaluation_expectation" not in self._stubs: + self._stubs["delete_evaluation_expectation"] = ( + self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/DeleteEvaluationExpectation", + request_serializer=evaluation_service.DeleteEvaluationExpectationRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + ) + return self._stubs["delete_evaluation_expectation"] + + @property + def create_scheduled_evaluation_run( + self, + ) -> Callable[ + [evaluation_service.CreateScheduledEvaluationRunRequest], + Awaitable[evaluation.ScheduledEvaluationRun], + ]: + r"""Return a callable for the create scheduled evaluation + run method over gRPC. + + Creates a scheduled evaluation run. + + Returns: + Callable[[~.CreateScheduledEvaluationRunRequest], + Awaitable[~.ScheduledEvaluationRun]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_scheduled_evaluation_run" not in self._stubs: + self._stubs["create_scheduled_evaluation_run"] = ( + self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/CreateScheduledEvaluationRun", + request_serializer=evaluation_service.CreateScheduledEvaluationRunRequest.serialize, + response_deserializer=evaluation.ScheduledEvaluationRun.deserialize, + ) + ) + return self._stubs["create_scheduled_evaluation_run"] + + @property + def get_scheduled_evaluation_run( + self, + ) -> Callable[ + [evaluation_service.GetScheduledEvaluationRunRequest], + Awaitable[evaluation.ScheduledEvaluationRun], + ]: + r"""Return a callable for the get scheduled evaluation run method over gRPC. + + Gets details of the specified scheduled evaluation + run. + + Returns: + Callable[[~.GetScheduledEvaluationRunRequest], + Awaitable[~.ScheduledEvaluationRun]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_scheduled_evaluation_run" not in self._stubs: + self._stubs["get_scheduled_evaluation_run"] = ( + self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/GetScheduledEvaluationRun", + request_serializer=evaluation_service.GetScheduledEvaluationRunRequest.serialize, + response_deserializer=evaluation.ScheduledEvaluationRun.deserialize, + ) + ) + return self._stubs["get_scheduled_evaluation_run"] + + @property + def list_scheduled_evaluation_runs( + self, + ) -> Callable[ + [evaluation_service.ListScheduledEvaluationRunsRequest], + Awaitable[evaluation_service.ListScheduledEvaluationRunsResponse], + ]: + r"""Return a callable for the list scheduled evaluation runs method over gRPC. + + Lists all scheduled evaluation runs in the given app. + + Returns: + Callable[[~.ListScheduledEvaluationRunsRequest], + Awaitable[~.ListScheduledEvaluationRunsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_scheduled_evaluation_runs" not in self._stubs: + self._stubs["list_scheduled_evaluation_runs"] = ( + self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/ListScheduledEvaluationRuns", + request_serializer=evaluation_service.ListScheduledEvaluationRunsRequest.serialize, + response_deserializer=evaluation_service.ListScheduledEvaluationRunsResponse.deserialize, + ) + ) + return self._stubs["list_scheduled_evaluation_runs"] + + @property + def update_scheduled_evaluation_run( + self, + ) -> Callable[ + [evaluation_service.UpdateScheduledEvaluationRunRequest], + Awaitable[evaluation.ScheduledEvaluationRun], + ]: + r"""Return a callable for the update scheduled evaluation + run method over gRPC. + + Updates a scheduled evaluation run. + + Returns: + Callable[[~.UpdateScheduledEvaluationRunRequest], + Awaitable[~.ScheduledEvaluationRun]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_scheduled_evaluation_run" not in self._stubs: + self._stubs["update_scheduled_evaluation_run"] = ( + self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/UpdateScheduledEvaluationRun", + request_serializer=evaluation_service.UpdateScheduledEvaluationRunRequest.serialize, + response_deserializer=evaluation.ScheduledEvaluationRun.deserialize, + ) + ) + return self._stubs["update_scheduled_evaluation_run"] + + @property + def delete_scheduled_evaluation_run( + self, + ) -> Callable[ + [evaluation_service.DeleteScheduledEvaluationRunRequest], + Awaitable[empty_pb2.Empty], + ]: + r"""Return a callable for the delete scheduled evaluation + run method over gRPC. + + Deletes a scheduled evaluation run. + + Returns: + Callable[[~.DeleteScheduledEvaluationRunRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_scheduled_evaluation_run" not in self._stubs: + self._stubs["delete_scheduled_evaluation_run"] = ( + self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/DeleteScheduledEvaluationRun", + request_serializer=evaluation_service.DeleteScheduledEvaluationRunRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + ) + return self._stubs["delete_scheduled_evaluation_run"] + + @property + def test_persona_voice( + self, + ) -> Callable[ + [evaluation_service.TestPersonaVoiceRequest], + Awaitable[evaluation_service.TestPersonaVoiceResponse], + ]: + r"""Return a callable for the test persona voice method over gRPC. + + Tests the voice of a persona. Also accepts a default + persona. + + Returns: + Callable[[~.TestPersonaVoiceRequest], + Awaitable[~.TestPersonaVoiceResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_persona_voice" not in self._stubs: + self._stubs["test_persona_voice"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.EvaluationService/TestPersonaVoice", + request_serializer=evaluation_service.TestPersonaVoiceRequest.serialize, + response_deserializer=evaluation_service.TestPersonaVoiceResponse.deserialize, + ) + return self._stubs["test_persona_voice"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.run_evaluation: self._wrap_method( + self.run_evaluation, + default_timeout=None, + client_info=client_info, + ), + self.upload_evaluation_audio: self._wrap_method( + self.upload_evaluation_audio, + default_timeout=None, + client_info=client_info, + ), + self.create_evaluation: self._wrap_method( + self.create_evaluation, + default_timeout=None, + client_info=client_info, + ), + self.generate_evaluation: self._wrap_method( + self.generate_evaluation, + default_timeout=None, + client_info=client_info, + ), + self.import_evaluations: self._wrap_method( + self.import_evaluations, + default_timeout=None, + client_info=client_info, + ), + self.create_evaluation_dataset: self._wrap_method( + self.create_evaluation_dataset, + default_timeout=None, + client_info=client_info, + ), + self.update_evaluation: self._wrap_method( + self.update_evaluation, + default_timeout=None, + client_info=client_info, + ), + self.update_evaluation_dataset: self._wrap_method( + self.update_evaluation_dataset, + default_timeout=None, + client_info=client_info, + ), + self.delete_evaluation: self._wrap_method( + self.delete_evaluation, + default_timeout=None, + client_info=client_info, + ), + self.delete_evaluation_result: self._wrap_method( + self.delete_evaluation_result, + default_timeout=None, + client_info=client_info, + ), + self.delete_evaluation_dataset: self._wrap_method( + self.delete_evaluation_dataset, + default_timeout=None, + client_info=client_info, + ), + self.delete_evaluation_run: self._wrap_method( + self.delete_evaluation_run, + default_timeout=None, + client_info=client_info, + ), + self.get_evaluation: self._wrap_method( + self.get_evaluation, + default_timeout=None, + client_info=client_info, + ), + self.get_evaluation_result: self._wrap_method( + self.get_evaluation_result, + default_timeout=None, + client_info=client_info, + ), + self.get_evaluation_dataset: self._wrap_method( + self.get_evaluation_dataset, + default_timeout=None, + client_info=client_info, + ), + self.get_evaluation_run: self._wrap_method( + self.get_evaluation_run, + default_timeout=None, + client_info=client_info, + ), + self.list_evaluations: self._wrap_method( + self.list_evaluations, + default_timeout=None, + client_info=client_info, + ), + self.list_evaluation_results: self._wrap_method( + self.list_evaluation_results, + default_timeout=None, + client_info=client_info, + ), + self.list_evaluation_datasets: self._wrap_method( + self.list_evaluation_datasets, + default_timeout=None, + client_info=client_info, + ), + self.list_evaluation_runs: self._wrap_method( + self.list_evaluation_runs, + default_timeout=None, + client_info=client_info, + ), + self.list_evaluation_expectations: self._wrap_method( + self.list_evaluation_expectations, + default_timeout=None, + client_info=client_info, + ), + self.get_evaluation_expectation: self._wrap_method( + self.get_evaluation_expectation, + default_timeout=None, + client_info=client_info, + ), + self.create_evaluation_expectation: self._wrap_method( + self.create_evaluation_expectation, + default_timeout=None, + client_info=client_info, + ), + self.update_evaluation_expectation: self._wrap_method( + self.update_evaluation_expectation, + default_timeout=None, + client_info=client_info, + ), + self.delete_evaluation_expectation: self._wrap_method( + self.delete_evaluation_expectation, + default_timeout=None, + client_info=client_info, + ), + self.create_scheduled_evaluation_run: self._wrap_method( + self.create_scheduled_evaluation_run, + default_timeout=None, + client_info=client_info, + ), + self.get_scheduled_evaluation_run: self._wrap_method( + self.get_scheduled_evaluation_run, + default_timeout=None, + client_info=client_info, + ), + self.list_scheduled_evaluation_runs: self._wrap_method( + self.list_scheduled_evaluation_runs, + default_timeout=None, + client_info=client_info, + ), + self.update_scheduled_evaluation_run: self._wrap_method( + self.update_scheduled_evaluation_run, + default_timeout=None, + client_info=client_info, + ), + self.delete_scheduled_evaluation_run: self._wrap_method( + self.delete_scheduled_evaluation_run, + default_timeout=None, + client_info=client_info, + ), + self.test_persona_voice: self._wrap_method( + self.test_persona_voice, + default_timeout=None, + client_info=client_info, + ), + self.get_location: self._wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: self._wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + +__all__ = ("EvaluationServiceGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/transports/rest.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/transports/rest.py new file mode 100644 index 000000000000..d2381d5e7928 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/transports/rest.py @@ -0,0 +1,7674 @@ +# -*- coding: utf-8 -*- +# 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. +# +import dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.ces_v1beta.types import evaluation, evaluation_service +from google.cloud.ces_v1beta.types import evaluation as gcc_evaluation + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseEvaluationServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class EvaluationServiceRestInterceptor: + """Interceptor for EvaluationService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the EvaluationServiceRestTransport. + + .. code-block:: python + class MyCustomEvaluationServiceInterceptor(EvaluationServiceRestInterceptor): + def pre_create_evaluation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_evaluation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_evaluation_dataset(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_evaluation_dataset(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_evaluation_expectation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_evaluation_expectation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_scheduled_evaluation_run(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_scheduled_evaluation_run(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_evaluation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_evaluation_dataset(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_evaluation_expectation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_evaluation_result(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_evaluation_run(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_evaluation_run(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_scheduled_evaluation_run(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_generate_evaluation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_generate_evaluation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_evaluation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_evaluation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_evaluation_dataset(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_evaluation_dataset(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_evaluation_expectation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_evaluation_expectation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_evaluation_result(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_evaluation_result(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_evaluation_run(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_evaluation_run(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_scheduled_evaluation_run(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_scheduled_evaluation_run(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_import_evaluations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_import_evaluations(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_evaluation_datasets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_evaluation_datasets(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_evaluation_expectations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_evaluation_expectations(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_evaluation_results(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_evaluation_results(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_evaluation_runs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_evaluation_runs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_evaluations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_evaluations(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_scheduled_evaluation_runs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_scheduled_evaluation_runs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_run_evaluation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_run_evaluation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_test_persona_voice(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_test_persona_voice(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_evaluation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_evaluation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_evaluation_dataset(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_evaluation_dataset(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_evaluation_expectation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_evaluation_expectation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_scheduled_evaluation_run(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_scheduled_evaluation_run(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_upload_evaluation_audio(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_upload_evaluation_audio(self, response): + logging.log(f"Received response: {response}") + return response + + transport = EvaluationServiceRestTransport(interceptor=MyCustomEvaluationServiceInterceptor()) + client = EvaluationServiceClient(transport=transport) + + + """ + + def pre_create_evaluation( + self, + request: evaluation_service.CreateEvaluationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation_service.CreateEvaluationRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_evaluation + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_create_evaluation( + self, response: gcc_evaluation.Evaluation + ) -> gcc_evaluation.Evaluation: + """Post-rpc interceptor for create_evaluation + + DEPRECATED. Please use the `post_create_evaluation_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the EvaluationService server but before + it is returned to user code. This `post_create_evaluation` interceptor runs + before the `post_create_evaluation_with_metadata` interceptor. + """ + return response + + def post_create_evaluation_with_metadata( + self, + response: gcc_evaluation.Evaluation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gcc_evaluation.Evaluation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_evaluation + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the EvaluationService server but before it is returned to user code. + + We recommend only using this `post_create_evaluation_with_metadata` + interceptor in new development instead of the `post_create_evaluation` interceptor. + When both interceptors are used, this `post_create_evaluation_with_metadata` interceptor runs after the + `post_create_evaluation` interceptor. The (possibly modified) response returned by + `post_create_evaluation` will be passed to + `post_create_evaluation_with_metadata`. + """ + return response, metadata + + def pre_create_evaluation_dataset( + self, + request: evaluation_service.CreateEvaluationDatasetRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation_service.CreateEvaluationDatasetRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_evaluation_dataset + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_create_evaluation_dataset( + self, response: evaluation.EvaluationDataset + ) -> evaluation.EvaluationDataset: + """Post-rpc interceptor for create_evaluation_dataset + + DEPRECATED. Please use the `post_create_evaluation_dataset_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the EvaluationService server but before + it is returned to user code. This `post_create_evaluation_dataset` interceptor runs + before the `post_create_evaluation_dataset_with_metadata` interceptor. + """ + return response + + def post_create_evaluation_dataset_with_metadata( + self, + response: evaluation.EvaluationDataset, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[evaluation.EvaluationDataset, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_evaluation_dataset + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the EvaluationService server but before it is returned to user code. + + We recommend only using this `post_create_evaluation_dataset_with_metadata` + interceptor in new development instead of the `post_create_evaluation_dataset` interceptor. + When both interceptors are used, this `post_create_evaluation_dataset_with_metadata` interceptor runs after the + `post_create_evaluation_dataset` interceptor. The (possibly modified) response returned by + `post_create_evaluation_dataset` will be passed to + `post_create_evaluation_dataset_with_metadata`. + """ + return response, metadata + + def pre_create_evaluation_expectation( + self, + request: evaluation_service.CreateEvaluationExpectationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation_service.CreateEvaluationExpectationRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_evaluation_expectation + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_create_evaluation_expectation( + self, response: evaluation.EvaluationExpectation + ) -> evaluation.EvaluationExpectation: + """Post-rpc interceptor for create_evaluation_expectation + + DEPRECATED. Please use the `post_create_evaluation_expectation_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the EvaluationService server but before + it is returned to user code. This `post_create_evaluation_expectation` interceptor runs + before the `post_create_evaluation_expectation_with_metadata` interceptor. + """ + return response + + def post_create_evaluation_expectation_with_metadata( + self, + response: evaluation.EvaluationExpectation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation.EvaluationExpectation, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for create_evaluation_expectation + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the EvaluationService server but before it is returned to user code. + + We recommend only using this `post_create_evaluation_expectation_with_metadata` + interceptor in new development instead of the `post_create_evaluation_expectation` interceptor. + When both interceptors are used, this `post_create_evaluation_expectation_with_metadata` interceptor runs after the + `post_create_evaluation_expectation` interceptor. The (possibly modified) response returned by + `post_create_evaluation_expectation` will be passed to + `post_create_evaluation_expectation_with_metadata`. + """ + return response, metadata + + def pre_create_scheduled_evaluation_run( + self, + request: evaluation_service.CreateScheduledEvaluationRunRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation_service.CreateScheduledEvaluationRunRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_scheduled_evaluation_run + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_create_scheduled_evaluation_run( + self, response: evaluation.ScheduledEvaluationRun + ) -> evaluation.ScheduledEvaluationRun: + """Post-rpc interceptor for create_scheduled_evaluation_run + + DEPRECATED. Please use the `post_create_scheduled_evaluation_run_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the EvaluationService server but before + it is returned to user code. This `post_create_scheduled_evaluation_run` interceptor runs + before the `post_create_scheduled_evaluation_run_with_metadata` interceptor. + """ + return response + + def post_create_scheduled_evaluation_run_with_metadata( + self, + response: evaluation.ScheduledEvaluationRun, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation.ScheduledEvaluationRun, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for create_scheduled_evaluation_run + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the EvaluationService server but before it is returned to user code. + + We recommend only using this `post_create_scheduled_evaluation_run_with_metadata` + interceptor in new development instead of the `post_create_scheduled_evaluation_run` interceptor. + When both interceptors are used, this `post_create_scheduled_evaluation_run_with_metadata` interceptor runs after the + `post_create_scheduled_evaluation_run` interceptor. The (possibly modified) response returned by + `post_create_scheduled_evaluation_run` will be passed to + `post_create_scheduled_evaluation_run_with_metadata`. + """ + return response, metadata + + def pre_delete_evaluation( + self, + request: evaluation_service.DeleteEvaluationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation_service.DeleteEvaluationRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_evaluation + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def pre_delete_evaluation_dataset( + self, + request: evaluation_service.DeleteEvaluationDatasetRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation_service.DeleteEvaluationDatasetRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_evaluation_dataset + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def pre_delete_evaluation_expectation( + self, + request: evaluation_service.DeleteEvaluationExpectationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation_service.DeleteEvaluationExpectationRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_evaluation_expectation + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def pre_delete_evaluation_result( + self, + request: evaluation_service.DeleteEvaluationResultRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation_service.DeleteEvaluationResultRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_evaluation_result + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def pre_delete_evaluation_run( + self, + request: evaluation_service.DeleteEvaluationRunRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation_service.DeleteEvaluationRunRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_evaluation_run + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_delete_evaluation_run( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_evaluation_run + + DEPRECATED. Please use the `post_delete_evaluation_run_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the EvaluationService server but before + it is returned to user code. This `post_delete_evaluation_run` interceptor runs + before the `post_delete_evaluation_run_with_metadata` interceptor. + """ + return response + + def post_delete_evaluation_run_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_evaluation_run + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the EvaluationService server but before it is returned to user code. + + We recommend only using this `post_delete_evaluation_run_with_metadata` + interceptor in new development instead of the `post_delete_evaluation_run` interceptor. + When both interceptors are used, this `post_delete_evaluation_run_with_metadata` interceptor runs after the + `post_delete_evaluation_run` interceptor. The (possibly modified) response returned by + `post_delete_evaluation_run` will be passed to + `post_delete_evaluation_run_with_metadata`. + """ + return response, metadata + + def pre_delete_scheduled_evaluation_run( + self, + request: evaluation_service.DeleteScheduledEvaluationRunRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation_service.DeleteScheduledEvaluationRunRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_scheduled_evaluation_run + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def pre_generate_evaluation( + self, + request: evaluation_service.GenerateEvaluationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation_service.GenerateEvaluationRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for generate_evaluation + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_generate_evaluation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for generate_evaluation + + DEPRECATED. Please use the `post_generate_evaluation_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the EvaluationService server but before + it is returned to user code. This `post_generate_evaluation` interceptor runs + before the `post_generate_evaluation_with_metadata` interceptor. + """ + return response + + def post_generate_evaluation_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for generate_evaluation + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the EvaluationService server but before it is returned to user code. + + We recommend only using this `post_generate_evaluation_with_metadata` + interceptor in new development instead of the `post_generate_evaluation` interceptor. + When both interceptors are used, this `post_generate_evaluation_with_metadata` interceptor runs after the + `post_generate_evaluation` interceptor. The (possibly modified) response returned by + `post_generate_evaluation` will be passed to + `post_generate_evaluation_with_metadata`. + """ + return response, metadata + + def pre_get_evaluation( + self, + request: evaluation_service.GetEvaluationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation_service.GetEvaluationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_evaluation + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_get_evaluation( + self, response: evaluation.Evaluation + ) -> evaluation.Evaluation: + """Post-rpc interceptor for get_evaluation + + DEPRECATED. Please use the `post_get_evaluation_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the EvaluationService server but before + it is returned to user code. This `post_get_evaluation` interceptor runs + before the `post_get_evaluation_with_metadata` interceptor. + """ + return response + + def post_get_evaluation_with_metadata( + self, + response: evaluation.Evaluation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[evaluation.Evaluation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_evaluation + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the EvaluationService server but before it is returned to user code. + + We recommend only using this `post_get_evaluation_with_metadata` + interceptor in new development instead of the `post_get_evaluation` interceptor. + When both interceptors are used, this `post_get_evaluation_with_metadata` interceptor runs after the + `post_get_evaluation` interceptor. The (possibly modified) response returned by + `post_get_evaluation` will be passed to + `post_get_evaluation_with_metadata`. + """ + return response, metadata + + def pre_get_evaluation_dataset( + self, + request: evaluation_service.GetEvaluationDatasetRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation_service.GetEvaluationDatasetRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_evaluation_dataset + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_get_evaluation_dataset( + self, response: evaluation.EvaluationDataset + ) -> evaluation.EvaluationDataset: + """Post-rpc interceptor for get_evaluation_dataset + + DEPRECATED. Please use the `post_get_evaluation_dataset_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the EvaluationService server but before + it is returned to user code. This `post_get_evaluation_dataset` interceptor runs + before the `post_get_evaluation_dataset_with_metadata` interceptor. + """ + return response + + def post_get_evaluation_dataset_with_metadata( + self, + response: evaluation.EvaluationDataset, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[evaluation.EvaluationDataset, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_evaluation_dataset + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the EvaluationService server but before it is returned to user code. + + We recommend only using this `post_get_evaluation_dataset_with_metadata` + interceptor in new development instead of the `post_get_evaluation_dataset` interceptor. + When both interceptors are used, this `post_get_evaluation_dataset_with_metadata` interceptor runs after the + `post_get_evaluation_dataset` interceptor. The (possibly modified) response returned by + `post_get_evaluation_dataset` will be passed to + `post_get_evaluation_dataset_with_metadata`. + """ + return response, metadata + + def pre_get_evaluation_expectation( + self, + request: evaluation_service.GetEvaluationExpectationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation_service.GetEvaluationExpectationRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_evaluation_expectation + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_get_evaluation_expectation( + self, response: evaluation.EvaluationExpectation + ) -> evaluation.EvaluationExpectation: + """Post-rpc interceptor for get_evaluation_expectation + + DEPRECATED. Please use the `post_get_evaluation_expectation_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the EvaluationService server but before + it is returned to user code. This `post_get_evaluation_expectation` interceptor runs + before the `post_get_evaluation_expectation_with_metadata` interceptor. + """ + return response + + def post_get_evaluation_expectation_with_metadata( + self, + response: evaluation.EvaluationExpectation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation.EvaluationExpectation, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for get_evaluation_expectation + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the EvaluationService server but before it is returned to user code. + + We recommend only using this `post_get_evaluation_expectation_with_metadata` + interceptor in new development instead of the `post_get_evaluation_expectation` interceptor. + When both interceptors are used, this `post_get_evaluation_expectation_with_metadata` interceptor runs after the + `post_get_evaluation_expectation` interceptor. The (possibly modified) response returned by + `post_get_evaluation_expectation` will be passed to + `post_get_evaluation_expectation_with_metadata`. + """ + return response, metadata + + def pre_get_evaluation_result( + self, + request: evaluation_service.GetEvaluationResultRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation_service.GetEvaluationResultRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_evaluation_result + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_get_evaluation_result( + self, response: evaluation.EvaluationResult + ) -> evaluation.EvaluationResult: + """Post-rpc interceptor for get_evaluation_result + + DEPRECATED. Please use the `post_get_evaluation_result_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the EvaluationService server but before + it is returned to user code. This `post_get_evaluation_result` interceptor runs + before the `post_get_evaluation_result_with_metadata` interceptor. + """ + return response + + def post_get_evaluation_result_with_metadata( + self, + response: evaluation.EvaluationResult, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[evaluation.EvaluationResult, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_evaluation_result + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the EvaluationService server but before it is returned to user code. + + We recommend only using this `post_get_evaluation_result_with_metadata` + interceptor in new development instead of the `post_get_evaluation_result` interceptor. + When both interceptors are used, this `post_get_evaluation_result_with_metadata` interceptor runs after the + `post_get_evaluation_result` interceptor. The (possibly modified) response returned by + `post_get_evaluation_result` will be passed to + `post_get_evaluation_result_with_metadata`. + """ + return response, metadata + + def pre_get_evaluation_run( + self, + request: evaluation_service.GetEvaluationRunRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation_service.GetEvaluationRunRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_evaluation_run + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_get_evaluation_run( + self, response: evaluation.EvaluationRun + ) -> evaluation.EvaluationRun: + """Post-rpc interceptor for get_evaluation_run + + DEPRECATED. Please use the `post_get_evaluation_run_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the EvaluationService server but before + it is returned to user code. This `post_get_evaluation_run` interceptor runs + before the `post_get_evaluation_run_with_metadata` interceptor. + """ + return response + + def post_get_evaluation_run_with_metadata( + self, + response: evaluation.EvaluationRun, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[evaluation.EvaluationRun, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_evaluation_run + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the EvaluationService server but before it is returned to user code. + + We recommend only using this `post_get_evaluation_run_with_metadata` + interceptor in new development instead of the `post_get_evaluation_run` interceptor. + When both interceptors are used, this `post_get_evaluation_run_with_metadata` interceptor runs after the + `post_get_evaluation_run` interceptor. The (possibly modified) response returned by + `post_get_evaluation_run` will be passed to + `post_get_evaluation_run_with_metadata`. + """ + return response, metadata + + def pre_get_scheduled_evaluation_run( + self, + request: evaluation_service.GetScheduledEvaluationRunRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation_service.GetScheduledEvaluationRunRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_scheduled_evaluation_run + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_get_scheduled_evaluation_run( + self, response: evaluation.ScheduledEvaluationRun + ) -> evaluation.ScheduledEvaluationRun: + """Post-rpc interceptor for get_scheduled_evaluation_run + + DEPRECATED. Please use the `post_get_scheduled_evaluation_run_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the EvaluationService server but before + it is returned to user code. This `post_get_scheduled_evaluation_run` interceptor runs + before the `post_get_scheduled_evaluation_run_with_metadata` interceptor. + """ + return response + + def post_get_scheduled_evaluation_run_with_metadata( + self, + response: evaluation.ScheduledEvaluationRun, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation.ScheduledEvaluationRun, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for get_scheduled_evaluation_run + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the EvaluationService server but before it is returned to user code. + + We recommend only using this `post_get_scheduled_evaluation_run_with_metadata` + interceptor in new development instead of the `post_get_scheduled_evaluation_run` interceptor. + When both interceptors are used, this `post_get_scheduled_evaluation_run_with_metadata` interceptor runs after the + `post_get_scheduled_evaluation_run` interceptor. The (possibly modified) response returned by + `post_get_scheduled_evaluation_run` will be passed to + `post_get_scheduled_evaluation_run_with_metadata`. + """ + return response, metadata + + def pre_import_evaluations( + self, + request: evaluation_service.ImportEvaluationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation_service.ImportEvaluationsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for import_evaluations + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_import_evaluations( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for import_evaluations + + DEPRECATED. Please use the `post_import_evaluations_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the EvaluationService server but before + it is returned to user code. This `post_import_evaluations` interceptor runs + before the `post_import_evaluations_with_metadata` interceptor. + """ + return response + + def post_import_evaluations_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for import_evaluations + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the EvaluationService server but before it is returned to user code. + + We recommend only using this `post_import_evaluations_with_metadata` + interceptor in new development instead of the `post_import_evaluations` interceptor. + When both interceptors are used, this `post_import_evaluations_with_metadata` interceptor runs after the + `post_import_evaluations` interceptor. The (possibly modified) response returned by + `post_import_evaluations` will be passed to + `post_import_evaluations_with_metadata`. + """ + return response, metadata + + def pre_list_evaluation_datasets( + self, + request: evaluation_service.ListEvaluationDatasetsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation_service.ListEvaluationDatasetsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_evaluation_datasets + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_list_evaluation_datasets( + self, response: evaluation_service.ListEvaluationDatasetsResponse + ) -> evaluation_service.ListEvaluationDatasetsResponse: + """Post-rpc interceptor for list_evaluation_datasets + + DEPRECATED. Please use the `post_list_evaluation_datasets_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the EvaluationService server but before + it is returned to user code. This `post_list_evaluation_datasets` interceptor runs + before the `post_list_evaluation_datasets_with_metadata` interceptor. + """ + return response + + def post_list_evaluation_datasets_with_metadata( + self, + response: evaluation_service.ListEvaluationDatasetsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation_service.ListEvaluationDatasetsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_evaluation_datasets + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the EvaluationService server but before it is returned to user code. + + We recommend only using this `post_list_evaluation_datasets_with_metadata` + interceptor in new development instead of the `post_list_evaluation_datasets` interceptor. + When both interceptors are used, this `post_list_evaluation_datasets_with_metadata` interceptor runs after the + `post_list_evaluation_datasets` interceptor. The (possibly modified) response returned by + `post_list_evaluation_datasets` will be passed to + `post_list_evaluation_datasets_with_metadata`. + """ + return response, metadata + + def pre_list_evaluation_expectations( + self, + request: evaluation_service.ListEvaluationExpectationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation_service.ListEvaluationExpectationsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_evaluation_expectations + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_list_evaluation_expectations( + self, response: evaluation_service.ListEvaluationExpectationsResponse + ) -> evaluation_service.ListEvaluationExpectationsResponse: + """Post-rpc interceptor for list_evaluation_expectations + + DEPRECATED. Please use the `post_list_evaluation_expectations_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the EvaluationService server but before + it is returned to user code. This `post_list_evaluation_expectations` interceptor runs + before the `post_list_evaluation_expectations_with_metadata` interceptor. + """ + return response + + def post_list_evaluation_expectations_with_metadata( + self, + response: evaluation_service.ListEvaluationExpectationsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation_service.ListEvaluationExpectationsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_evaluation_expectations + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the EvaluationService server but before it is returned to user code. + + We recommend only using this `post_list_evaluation_expectations_with_metadata` + interceptor in new development instead of the `post_list_evaluation_expectations` interceptor. + When both interceptors are used, this `post_list_evaluation_expectations_with_metadata` interceptor runs after the + `post_list_evaluation_expectations` interceptor. The (possibly modified) response returned by + `post_list_evaluation_expectations` will be passed to + `post_list_evaluation_expectations_with_metadata`. + """ + return response, metadata + + def pre_list_evaluation_results( + self, + request: evaluation_service.ListEvaluationResultsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation_service.ListEvaluationResultsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_evaluation_results + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_list_evaluation_results( + self, response: evaluation_service.ListEvaluationResultsResponse + ) -> evaluation_service.ListEvaluationResultsResponse: + """Post-rpc interceptor for list_evaluation_results + + DEPRECATED. Please use the `post_list_evaluation_results_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the EvaluationService server but before + it is returned to user code. This `post_list_evaluation_results` interceptor runs + before the `post_list_evaluation_results_with_metadata` interceptor. + """ + return response + + def post_list_evaluation_results_with_metadata( + self, + response: evaluation_service.ListEvaluationResultsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation_service.ListEvaluationResultsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_evaluation_results + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the EvaluationService server but before it is returned to user code. + + We recommend only using this `post_list_evaluation_results_with_metadata` + interceptor in new development instead of the `post_list_evaluation_results` interceptor. + When both interceptors are used, this `post_list_evaluation_results_with_metadata` interceptor runs after the + `post_list_evaluation_results` interceptor. The (possibly modified) response returned by + `post_list_evaluation_results` will be passed to + `post_list_evaluation_results_with_metadata`. + """ + return response, metadata + + def pre_list_evaluation_runs( + self, + request: evaluation_service.ListEvaluationRunsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation_service.ListEvaluationRunsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_evaluation_runs + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_list_evaluation_runs( + self, response: evaluation_service.ListEvaluationRunsResponse + ) -> evaluation_service.ListEvaluationRunsResponse: + """Post-rpc interceptor for list_evaluation_runs + + DEPRECATED. Please use the `post_list_evaluation_runs_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the EvaluationService server but before + it is returned to user code. This `post_list_evaluation_runs` interceptor runs + before the `post_list_evaluation_runs_with_metadata` interceptor. + """ + return response + + def post_list_evaluation_runs_with_metadata( + self, + response: evaluation_service.ListEvaluationRunsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation_service.ListEvaluationRunsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_evaluation_runs + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the EvaluationService server but before it is returned to user code. + + We recommend only using this `post_list_evaluation_runs_with_metadata` + interceptor in new development instead of the `post_list_evaluation_runs` interceptor. + When both interceptors are used, this `post_list_evaluation_runs_with_metadata` interceptor runs after the + `post_list_evaluation_runs` interceptor. The (possibly modified) response returned by + `post_list_evaluation_runs` will be passed to + `post_list_evaluation_runs_with_metadata`. + """ + return response, metadata + + def pre_list_evaluations( + self, + request: evaluation_service.ListEvaluationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation_service.ListEvaluationsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_evaluations + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_list_evaluations( + self, response: evaluation_service.ListEvaluationsResponse + ) -> evaluation_service.ListEvaluationsResponse: + """Post-rpc interceptor for list_evaluations + + DEPRECATED. Please use the `post_list_evaluations_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the EvaluationService server but before + it is returned to user code. This `post_list_evaluations` interceptor runs + before the `post_list_evaluations_with_metadata` interceptor. + """ + return response + + def post_list_evaluations_with_metadata( + self, + response: evaluation_service.ListEvaluationsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation_service.ListEvaluationsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_evaluations + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the EvaluationService server but before it is returned to user code. + + We recommend only using this `post_list_evaluations_with_metadata` + interceptor in new development instead of the `post_list_evaluations` interceptor. + When both interceptors are used, this `post_list_evaluations_with_metadata` interceptor runs after the + `post_list_evaluations` interceptor. The (possibly modified) response returned by + `post_list_evaluations` will be passed to + `post_list_evaluations_with_metadata`. + """ + return response, metadata + + def pre_list_scheduled_evaluation_runs( + self, + request: evaluation_service.ListScheduledEvaluationRunsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation_service.ListScheduledEvaluationRunsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_scheduled_evaluation_runs + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_list_scheduled_evaluation_runs( + self, response: evaluation_service.ListScheduledEvaluationRunsResponse + ) -> evaluation_service.ListScheduledEvaluationRunsResponse: + """Post-rpc interceptor for list_scheduled_evaluation_runs + + DEPRECATED. Please use the `post_list_scheduled_evaluation_runs_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the EvaluationService server but before + it is returned to user code. This `post_list_scheduled_evaluation_runs` interceptor runs + before the `post_list_scheduled_evaluation_runs_with_metadata` interceptor. + """ + return response + + def post_list_scheduled_evaluation_runs_with_metadata( + self, + response: evaluation_service.ListScheduledEvaluationRunsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation_service.ListScheduledEvaluationRunsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_scheduled_evaluation_runs + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the EvaluationService server but before it is returned to user code. + + We recommend only using this `post_list_scheduled_evaluation_runs_with_metadata` + interceptor in new development instead of the `post_list_scheduled_evaluation_runs` interceptor. + When both interceptors are used, this `post_list_scheduled_evaluation_runs_with_metadata` interceptor runs after the + `post_list_scheduled_evaluation_runs` interceptor. The (possibly modified) response returned by + `post_list_scheduled_evaluation_runs` will be passed to + `post_list_scheduled_evaluation_runs_with_metadata`. + """ + return response, metadata + + def pre_run_evaluation( + self, + request: evaluation.RunEvaluationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation.RunEvaluationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for run_evaluation + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_run_evaluation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for run_evaluation + + DEPRECATED. Please use the `post_run_evaluation_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the EvaluationService server but before + it is returned to user code. This `post_run_evaluation` interceptor runs + before the `post_run_evaluation_with_metadata` interceptor. + """ + return response + + def post_run_evaluation_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for run_evaluation + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the EvaluationService server but before it is returned to user code. + + We recommend only using this `post_run_evaluation_with_metadata` + interceptor in new development instead of the `post_run_evaluation` interceptor. + When both interceptors are used, this `post_run_evaluation_with_metadata` interceptor runs after the + `post_run_evaluation` interceptor. The (possibly modified) response returned by + `post_run_evaluation` will be passed to + `post_run_evaluation_with_metadata`. + """ + return response, metadata + + def pre_test_persona_voice( + self, + request: evaluation_service.TestPersonaVoiceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation_service.TestPersonaVoiceRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for test_persona_voice + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_test_persona_voice( + self, response: evaluation_service.TestPersonaVoiceResponse + ) -> evaluation_service.TestPersonaVoiceResponse: + """Post-rpc interceptor for test_persona_voice + + DEPRECATED. Please use the `post_test_persona_voice_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the EvaluationService server but before + it is returned to user code. This `post_test_persona_voice` interceptor runs + before the `post_test_persona_voice_with_metadata` interceptor. + """ + return response + + def post_test_persona_voice_with_metadata( + self, + response: evaluation_service.TestPersonaVoiceResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation_service.TestPersonaVoiceResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for test_persona_voice + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the EvaluationService server but before it is returned to user code. + + We recommend only using this `post_test_persona_voice_with_metadata` + interceptor in new development instead of the `post_test_persona_voice` interceptor. + When both interceptors are used, this `post_test_persona_voice_with_metadata` interceptor runs after the + `post_test_persona_voice` interceptor. The (possibly modified) response returned by + `post_test_persona_voice` will be passed to + `post_test_persona_voice_with_metadata`. + """ + return response, metadata + + def pre_update_evaluation( + self, + request: evaluation_service.UpdateEvaluationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation_service.UpdateEvaluationRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_evaluation + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_update_evaluation( + self, response: gcc_evaluation.Evaluation + ) -> gcc_evaluation.Evaluation: + """Post-rpc interceptor for update_evaluation + + DEPRECATED. Please use the `post_update_evaluation_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the EvaluationService server but before + it is returned to user code. This `post_update_evaluation` interceptor runs + before the `post_update_evaluation_with_metadata` interceptor. + """ + return response + + def post_update_evaluation_with_metadata( + self, + response: gcc_evaluation.Evaluation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gcc_evaluation.Evaluation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_evaluation + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the EvaluationService server but before it is returned to user code. + + We recommend only using this `post_update_evaluation_with_metadata` + interceptor in new development instead of the `post_update_evaluation` interceptor. + When both interceptors are used, this `post_update_evaluation_with_metadata` interceptor runs after the + `post_update_evaluation` interceptor. The (possibly modified) response returned by + `post_update_evaluation` will be passed to + `post_update_evaluation_with_metadata`. + """ + return response, metadata + + def pre_update_evaluation_dataset( + self, + request: evaluation_service.UpdateEvaluationDatasetRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation_service.UpdateEvaluationDatasetRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_evaluation_dataset + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_update_evaluation_dataset( + self, response: evaluation.EvaluationDataset + ) -> evaluation.EvaluationDataset: + """Post-rpc interceptor for update_evaluation_dataset + + DEPRECATED. Please use the `post_update_evaluation_dataset_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the EvaluationService server but before + it is returned to user code. This `post_update_evaluation_dataset` interceptor runs + before the `post_update_evaluation_dataset_with_metadata` interceptor. + """ + return response + + def post_update_evaluation_dataset_with_metadata( + self, + response: evaluation.EvaluationDataset, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[evaluation.EvaluationDataset, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_evaluation_dataset + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the EvaluationService server but before it is returned to user code. + + We recommend only using this `post_update_evaluation_dataset_with_metadata` + interceptor in new development instead of the `post_update_evaluation_dataset` interceptor. + When both interceptors are used, this `post_update_evaluation_dataset_with_metadata` interceptor runs after the + `post_update_evaluation_dataset` interceptor. The (possibly modified) response returned by + `post_update_evaluation_dataset` will be passed to + `post_update_evaluation_dataset_with_metadata`. + """ + return response, metadata + + def pre_update_evaluation_expectation( + self, + request: evaluation_service.UpdateEvaluationExpectationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation_service.UpdateEvaluationExpectationRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_evaluation_expectation + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_update_evaluation_expectation( + self, response: evaluation.EvaluationExpectation + ) -> evaluation.EvaluationExpectation: + """Post-rpc interceptor for update_evaluation_expectation + + DEPRECATED. Please use the `post_update_evaluation_expectation_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the EvaluationService server but before + it is returned to user code. This `post_update_evaluation_expectation` interceptor runs + before the `post_update_evaluation_expectation_with_metadata` interceptor. + """ + return response + + def post_update_evaluation_expectation_with_metadata( + self, + response: evaluation.EvaluationExpectation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation.EvaluationExpectation, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for update_evaluation_expectation + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the EvaluationService server but before it is returned to user code. + + We recommend only using this `post_update_evaluation_expectation_with_metadata` + interceptor in new development instead of the `post_update_evaluation_expectation` interceptor. + When both interceptors are used, this `post_update_evaluation_expectation_with_metadata` interceptor runs after the + `post_update_evaluation_expectation` interceptor. The (possibly modified) response returned by + `post_update_evaluation_expectation` will be passed to + `post_update_evaluation_expectation_with_metadata`. + """ + return response, metadata + + def pre_update_scheduled_evaluation_run( + self, + request: evaluation_service.UpdateScheduledEvaluationRunRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation_service.UpdateScheduledEvaluationRunRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_scheduled_evaluation_run + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_update_scheduled_evaluation_run( + self, response: evaluation.ScheduledEvaluationRun + ) -> evaluation.ScheduledEvaluationRun: + """Post-rpc interceptor for update_scheduled_evaluation_run + + DEPRECATED. Please use the `post_update_scheduled_evaluation_run_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the EvaluationService server but before + it is returned to user code. This `post_update_scheduled_evaluation_run` interceptor runs + before the `post_update_scheduled_evaluation_run_with_metadata` interceptor. + """ + return response + + def post_update_scheduled_evaluation_run_with_metadata( + self, + response: evaluation.ScheduledEvaluationRun, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation.ScheduledEvaluationRun, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for update_scheduled_evaluation_run + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the EvaluationService server but before it is returned to user code. + + We recommend only using this `post_update_scheduled_evaluation_run_with_metadata` + interceptor in new development instead of the `post_update_scheduled_evaluation_run` interceptor. + When both interceptors are used, this `post_update_scheduled_evaluation_run_with_metadata` interceptor runs after the + `post_update_scheduled_evaluation_run` interceptor. The (possibly modified) response returned by + `post_update_scheduled_evaluation_run` will be passed to + `post_update_scheduled_evaluation_run_with_metadata`. + """ + return response, metadata + + def pre_upload_evaluation_audio( + self, + request: evaluation_service.UploadEvaluationAudioRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation_service.UploadEvaluationAudioRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for upload_evaluation_audio + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_upload_evaluation_audio( + self, response: evaluation_service.UploadEvaluationAudioResponse + ) -> evaluation_service.UploadEvaluationAudioResponse: + """Post-rpc interceptor for upload_evaluation_audio + + DEPRECATED. Please use the `post_upload_evaluation_audio_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the EvaluationService server but before + it is returned to user code. This `post_upload_evaluation_audio` interceptor runs + before the `post_upload_evaluation_audio_with_metadata` interceptor. + """ + return response + + def post_upload_evaluation_audio_with_metadata( + self, + response: evaluation_service.UploadEvaluationAudioResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + evaluation_service.UploadEvaluationAudioResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for upload_evaluation_audio + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the EvaluationService server but before it is returned to user code. + + We recommend only using this `post_upload_evaluation_audio_with_metadata` + interceptor in new development instead of the `post_upload_evaluation_audio` interceptor. + When both interceptors are used, this `post_upload_evaluation_audio_with_metadata` interceptor runs after the + `post_upload_evaluation_audio` interceptor. The (possibly modified) response returned by + `post_upload_evaluation_audio` will be passed to + `post_upload_evaluation_audio_with_metadata`. + """ + return response, metadata + + def pre_get_location( + self, + request: locations_pb2.GetLocationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.Location + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the EvaluationService server but before + it is returned to user code. + """ + return response + + def pre_list_locations( + self, + request: locations_pb2.ListLocationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsResponse + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the EvaluationService server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_cancel_operation(self, response: None) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the EvaluationService server but before + it is returned to user code. + """ + return response + + def pre_delete_operation( + self, + request: operations_pb2.DeleteOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_delete_operation(self, response: None) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the EvaluationService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the EvaluationService server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the EvaluationService server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the EvaluationService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class EvaluationServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: EvaluationServiceRestInterceptor + + +class EvaluationServiceRestTransport(_BaseEvaluationServiceRestTransport): + """REST backend synchronous transport for EvaluationService. + + EvaluationService exposes methods to perform evaluation for + the CES app. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "ces.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[EvaluationServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'ces.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or EvaluationServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.CancelOperation": [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ], + "google.longrunning.Operations.DeleteOperation": [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*}/operations", + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1beta", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _CreateEvaluation( + _BaseEvaluationServiceRestTransport._BaseCreateEvaluation, + EvaluationServiceRestStub, + ): + def __hash__(self): + return hash("EvaluationServiceRestTransport.CreateEvaluation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: evaluation_service.CreateEvaluationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_evaluation.Evaluation: + r"""Call the create evaluation method over HTTP. + + Args: + request (~.evaluation_service.CreateEvaluationRequest): + The request object. Request message for + [EvaluationService.CreateEvaluation][google.cloud.ces.v1beta.EvaluationService.CreateEvaluation]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gcc_evaluation.Evaluation: + An evaluation represents all of the + information needed to simulate and + evaluate an agent. + + """ + + http_options = _BaseEvaluationServiceRestTransport._BaseCreateEvaluation._get_http_options() + + request, metadata = self._interceptor.pre_create_evaluation( + request, metadata + ) + transcoded_request = _BaseEvaluationServiceRestTransport._BaseCreateEvaluation._get_transcoded_request( + http_options, request + ) + + body = _BaseEvaluationServiceRestTransport._BaseCreateEvaluation._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseEvaluationServiceRestTransport._BaseCreateEvaluation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.EvaluationServiceClient.CreateEvaluation", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "CreateEvaluation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EvaluationServiceRestTransport._CreateEvaluation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcc_evaluation.Evaluation() + pb_resp = gcc_evaluation.Evaluation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_evaluation(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_evaluation_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gcc_evaluation.Evaluation.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.EvaluationServiceClient.create_evaluation", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "CreateEvaluation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateEvaluationDataset( + _BaseEvaluationServiceRestTransport._BaseCreateEvaluationDataset, + EvaluationServiceRestStub, + ): + def __hash__(self): + return hash("EvaluationServiceRestTransport.CreateEvaluationDataset") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: evaluation_service.CreateEvaluationDatasetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation.EvaluationDataset: + r"""Call the create evaluation dataset method over HTTP. + + Args: + request (~.evaluation_service.CreateEvaluationDatasetRequest): + The request object. Request message for + [EvaluationService.CreateEvaluationDataset][google.cloud.ces.v1beta.EvaluationService.CreateEvaluationDataset]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.evaluation.EvaluationDataset: + An evaluation dataset represents a + set of evaluations that are grouped + together basaed on shared tags. + + """ + + http_options = _BaseEvaluationServiceRestTransport._BaseCreateEvaluationDataset._get_http_options() + + request, metadata = self._interceptor.pre_create_evaluation_dataset( + request, metadata + ) + transcoded_request = _BaseEvaluationServiceRestTransport._BaseCreateEvaluationDataset._get_transcoded_request( + http_options, request + ) + + body = _BaseEvaluationServiceRestTransport._BaseCreateEvaluationDataset._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseEvaluationServiceRestTransport._BaseCreateEvaluationDataset._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.EvaluationServiceClient.CreateEvaluationDataset", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "CreateEvaluationDataset", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + EvaluationServiceRestTransport._CreateEvaluationDataset._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = evaluation.EvaluationDataset() + pb_resp = evaluation.EvaluationDataset.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_evaluation_dataset(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_evaluation_dataset_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = evaluation.EvaluationDataset.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.EvaluationServiceClient.create_evaluation_dataset", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "CreateEvaluationDataset", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateEvaluationExpectation( + _BaseEvaluationServiceRestTransport._BaseCreateEvaluationExpectation, + EvaluationServiceRestStub, + ): + def __hash__(self): + return hash("EvaluationServiceRestTransport.CreateEvaluationExpectation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: evaluation_service.CreateEvaluationExpectationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation.EvaluationExpectation: + r"""Call the create evaluation + expectation method over HTTP. + + Args: + request (~.evaluation_service.CreateEvaluationExpectationRequest): + The request object. Request message for + [EvaluationService.CreateEvaluationExpectation][google.cloud.ces.v1beta.EvaluationService.CreateEvaluationExpectation]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.evaluation.EvaluationExpectation: + An evaluation expectation represents + a specific criteria to evaluate against. + + """ + + http_options = _BaseEvaluationServiceRestTransport._BaseCreateEvaluationExpectation._get_http_options() + + request, metadata = self._interceptor.pre_create_evaluation_expectation( + request, metadata + ) + transcoded_request = _BaseEvaluationServiceRestTransport._BaseCreateEvaluationExpectation._get_transcoded_request( + http_options, request + ) + + body = _BaseEvaluationServiceRestTransport._BaseCreateEvaluationExpectation._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseEvaluationServiceRestTransport._BaseCreateEvaluationExpectation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.EvaluationServiceClient.CreateEvaluationExpectation", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "CreateEvaluationExpectation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EvaluationServiceRestTransport._CreateEvaluationExpectation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = evaluation.EvaluationExpectation() + pb_resp = evaluation.EvaluationExpectation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_evaluation_expectation(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_create_evaluation_expectation_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = evaluation.EvaluationExpectation.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.EvaluationServiceClient.create_evaluation_expectation", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "CreateEvaluationExpectation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateScheduledEvaluationRun( + _BaseEvaluationServiceRestTransport._BaseCreateScheduledEvaluationRun, + EvaluationServiceRestStub, + ): + def __hash__(self): + return hash("EvaluationServiceRestTransport.CreateScheduledEvaluationRun") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: evaluation_service.CreateScheduledEvaluationRunRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation.ScheduledEvaluationRun: + r"""Call the create scheduled + evaluation run method over HTTP. + + Args: + request (~.evaluation_service.CreateScheduledEvaluationRunRequest): + The request object. Request message for + [EvaluationService.CreateScheduledEvaluationRun][google.cloud.ces.v1beta.EvaluationService.CreateScheduledEvaluationRun]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.evaluation.ScheduledEvaluationRun: + Represents a scheduled evaluation run + configuration. + + """ + + http_options = _BaseEvaluationServiceRestTransport._BaseCreateScheduledEvaluationRun._get_http_options() + + request, metadata = self._interceptor.pre_create_scheduled_evaluation_run( + request, metadata + ) + transcoded_request = _BaseEvaluationServiceRestTransport._BaseCreateScheduledEvaluationRun._get_transcoded_request( + http_options, request + ) + + body = _BaseEvaluationServiceRestTransport._BaseCreateScheduledEvaluationRun._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseEvaluationServiceRestTransport._BaseCreateScheduledEvaluationRun._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.EvaluationServiceClient.CreateScheduledEvaluationRun", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "CreateScheduledEvaluationRun", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EvaluationServiceRestTransport._CreateScheduledEvaluationRun._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = evaluation.ScheduledEvaluationRun() + pb_resp = evaluation.ScheduledEvaluationRun.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_scheduled_evaluation_run(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_create_scheduled_evaluation_run_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = evaluation.ScheduledEvaluationRun.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.EvaluationServiceClient.create_scheduled_evaluation_run", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "CreateScheduledEvaluationRun", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteEvaluation( + _BaseEvaluationServiceRestTransport._BaseDeleteEvaluation, + EvaluationServiceRestStub, + ): + def __hash__(self): + return hash("EvaluationServiceRestTransport.DeleteEvaluation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: evaluation_service.DeleteEvaluationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete evaluation method over HTTP. + + Args: + request (~.evaluation_service.DeleteEvaluationRequest): + The request object. Request message for + [EvaluationService.DeleteEvaluation][google.cloud.ces.v1beta.EvaluationService.DeleteEvaluation]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseEvaluationServiceRestTransport._BaseDeleteEvaluation._get_http_options() + + request, metadata = self._interceptor.pre_delete_evaluation( + request, metadata + ) + transcoded_request = _BaseEvaluationServiceRestTransport._BaseDeleteEvaluation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseEvaluationServiceRestTransport._BaseDeleteEvaluation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.EvaluationServiceClient.DeleteEvaluation", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "DeleteEvaluation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EvaluationServiceRestTransport._DeleteEvaluation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteEvaluationDataset( + _BaseEvaluationServiceRestTransport._BaseDeleteEvaluationDataset, + EvaluationServiceRestStub, + ): + def __hash__(self): + return hash("EvaluationServiceRestTransport.DeleteEvaluationDataset") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: evaluation_service.DeleteEvaluationDatasetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete evaluation dataset method over HTTP. + + Args: + request (~.evaluation_service.DeleteEvaluationDatasetRequest): + The request object. Request message for + [EvaluationService.DeleteEvaluationDataset][google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationDataset]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseEvaluationServiceRestTransport._BaseDeleteEvaluationDataset._get_http_options() + + request, metadata = self._interceptor.pre_delete_evaluation_dataset( + request, metadata + ) + transcoded_request = _BaseEvaluationServiceRestTransport._BaseDeleteEvaluationDataset._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseEvaluationServiceRestTransport._BaseDeleteEvaluationDataset._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.EvaluationServiceClient.DeleteEvaluationDataset", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "DeleteEvaluationDataset", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + EvaluationServiceRestTransport._DeleteEvaluationDataset._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteEvaluationExpectation( + _BaseEvaluationServiceRestTransport._BaseDeleteEvaluationExpectation, + EvaluationServiceRestStub, + ): + def __hash__(self): + return hash("EvaluationServiceRestTransport.DeleteEvaluationExpectation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: evaluation_service.DeleteEvaluationExpectationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete evaluation + expectation method over HTTP. + + Args: + request (~.evaluation_service.DeleteEvaluationExpectationRequest): + The request object. Request message for + [EvaluationService.DeleteEvaluationExpectation][google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationExpectation]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseEvaluationServiceRestTransport._BaseDeleteEvaluationExpectation._get_http_options() + + request, metadata = self._interceptor.pre_delete_evaluation_expectation( + request, metadata + ) + transcoded_request = _BaseEvaluationServiceRestTransport._BaseDeleteEvaluationExpectation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseEvaluationServiceRestTransport._BaseDeleteEvaluationExpectation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.EvaluationServiceClient.DeleteEvaluationExpectation", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "DeleteEvaluationExpectation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EvaluationServiceRestTransport._DeleteEvaluationExpectation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteEvaluationResult( + _BaseEvaluationServiceRestTransport._BaseDeleteEvaluationResult, + EvaluationServiceRestStub, + ): + def __hash__(self): + return hash("EvaluationServiceRestTransport.DeleteEvaluationResult") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: evaluation_service.DeleteEvaluationResultRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete evaluation result method over HTTP. + + Args: + request (~.evaluation_service.DeleteEvaluationResultRequest): + The request object. Request message for + [EvaluationService.DeleteEvaluationResult][google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationResult]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseEvaluationServiceRestTransport._BaseDeleteEvaluationResult._get_http_options() + + request, metadata = self._interceptor.pre_delete_evaluation_result( + request, metadata + ) + transcoded_request = _BaseEvaluationServiceRestTransport._BaseDeleteEvaluationResult._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseEvaluationServiceRestTransport._BaseDeleteEvaluationResult._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.EvaluationServiceClient.DeleteEvaluationResult", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "DeleteEvaluationResult", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + EvaluationServiceRestTransport._DeleteEvaluationResult._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteEvaluationRun( + _BaseEvaluationServiceRestTransport._BaseDeleteEvaluationRun, + EvaluationServiceRestStub, + ): + def __hash__(self): + return hash("EvaluationServiceRestTransport.DeleteEvaluationRun") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: evaluation_service.DeleteEvaluationRunRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete evaluation run method over HTTP. + + Args: + request (~.evaluation_service.DeleteEvaluationRunRequest): + The request object. Request message for + [EvaluationService.DeleteEvaluationRun][google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationRun]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseEvaluationServiceRestTransport._BaseDeleteEvaluationRun._get_http_options() + + request, metadata = self._interceptor.pre_delete_evaluation_run( + request, metadata + ) + transcoded_request = _BaseEvaluationServiceRestTransport._BaseDeleteEvaluationRun._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseEvaluationServiceRestTransport._BaseDeleteEvaluationRun._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.EvaluationServiceClient.DeleteEvaluationRun", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "DeleteEvaluationRun", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + EvaluationServiceRestTransport._DeleteEvaluationRun._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_evaluation_run(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_evaluation_run_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.EvaluationServiceClient.delete_evaluation_run", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "DeleteEvaluationRun", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteScheduledEvaluationRun( + _BaseEvaluationServiceRestTransport._BaseDeleteScheduledEvaluationRun, + EvaluationServiceRestStub, + ): + def __hash__(self): + return hash("EvaluationServiceRestTransport.DeleteScheduledEvaluationRun") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: evaluation_service.DeleteScheduledEvaluationRunRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete scheduled + evaluation run method over HTTP. + + Args: + request (~.evaluation_service.DeleteScheduledEvaluationRunRequest): + The request object. Request message for + [EvaluationService.DeleteScheduledEvaluationRun][google.cloud.ces.v1beta.EvaluationService.DeleteScheduledEvaluationRun]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseEvaluationServiceRestTransport._BaseDeleteScheduledEvaluationRun._get_http_options() + + request, metadata = self._interceptor.pre_delete_scheduled_evaluation_run( + request, metadata + ) + transcoded_request = _BaseEvaluationServiceRestTransport._BaseDeleteScheduledEvaluationRun._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseEvaluationServiceRestTransport._BaseDeleteScheduledEvaluationRun._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.EvaluationServiceClient.DeleteScheduledEvaluationRun", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "DeleteScheduledEvaluationRun", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EvaluationServiceRestTransport._DeleteScheduledEvaluationRun._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _GenerateEvaluation( + _BaseEvaluationServiceRestTransport._BaseGenerateEvaluation, + EvaluationServiceRestStub, + ): + def __hash__(self): + return hash("EvaluationServiceRestTransport.GenerateEvaluation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: evaluation_service.GenerateEvaluationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the generate evaluation method over HTTP. + + Args: + request (~.evaluation_service.GenerateEvaluationRequest): + The request object. Request message for + [EvaluationService.GenerateEvaluation][google.cloud.ces.v1beta.EvaluationService.GenerateEvaluation]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseEvaluationServiceRestTransport._BaseGenerateEvaluation._get_http_options() + + request, metadata = self._interceptor.pre_generate_evaluation( + request, metadata + ) + transcoded_request = _BaseEvaluationServiceRestTransport._BaseGenerateEvaluation._get_transcoded_request( + http_options, request + ) + + body = _BaseEvaluationServiceRestTransport._BaseGenerateEvaluation._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseEvaluationServiceRestTransport._BaseGenerateEvaluation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.EvaluationServiceClient.GenerateEvaluation", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "GenerateEvaluation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EvaluationServiceRestTransport._GenerateEvaluation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_generate_evaluation(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_generate_evaluation_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.EvaluationServiceClient.generate_evaluation", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "GenerateEvaluation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetEvaluation( + _BaseEvaluationServiceRestTransport._BaseGetEvaluation, + EvaluationServiceRestStub, + ): + def __hash__(self): + return hash("EvaluationServiceRestTransport.GetEvaluation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: evaluation_service.GetEvaluationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation.Evaluation: + r"""Call the get evaluation method over HTTP. + + Args: + request (~.evaluation_service.GetEvaluationRequest): + The request object. Request message for + [EvaluationService.GetEvaluation][google.cloud.ces.v1beta.EvaluationService.GetEvaluation]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.evaluation.Evaluation: + An evaluation represents all of the + information needed to simulate and + evaluate an agent. + + """ + + http_options = _BaseEvaluationServiceRestTransport._BaseGetEvaluation._get_http_options() + + request, metadata = self._interceptor.pre_get_evaluation(request, metadata) + transcoded_request = _BaseEvaluationServiceRestTransport._BaseGetEvaluation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseEvaluationServiceRestTransport._BaseGetEvaluation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.EvaluationServiceClient.GetEvaluation", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "GetEvaluation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EvaluationServiceRestTransport._GetEvaluation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = evaluation.Evaluation() + pb_resp = evaluation.Evaluation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_evaluation(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_evaluation_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = evaluation.Evaluation.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.EvaluationServiceClient.get_evaluation", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "GetEvaluation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetEvaluationDataset( + _BaseEvaluationServiceRestTransport._BaseGetEvaluationDataset, + EvaluationServiceRestStub, + ): + def __hash__(self): + return hash("EvaluationServiceRestTransport.GetEvaluationDataset") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: evaluation_service.GetEvaluationDatasetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation.EvaluationDataset: + r"""Call the get evaluation dataset method over HTTP. + + Args: + request (~.evaluation_service.GetEvaluationDatasetRequest): + The request object. Request message for + [EvaluationService.GetEvaluationDataset][google.cloud.ces.v1beta.EvaluationService.GetEvaluationDataset]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.evaluation.EvaluationDataset: + An evaluation dataset represents a + set of evaluations that are grouped + together basaed on shared tags. + + """ + + http_options = _BaseEvaluationServiceRestTransport._BaseGetEvaluationDataset._get_http_options() + + request, metadata = self._interceptor.pre_get_evaluation_dataset( + request, metadata + ) + transcoded_request = _BaseEvaluationServiceRestTransport._BaseGetEvaluationDataset._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseEvaluationServiceRestTransport._BaseGetEvaluationDataset._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.EvaluationServiceClient.GetEvaluationDataset", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "GetEvaluationDataset", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + EvaluationServiceRestTransport._GetEvaluationDataset._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = evaluation.EvaluationDataset() + pb_resp = evaluation.EvaluationDataset.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_evaluation_dataset(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_evaluation_dataset_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = evaluation.EvaluationDataset.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.EvaluationServiceClient.get_evaluation_dataset", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "GetEvaluationDataset", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetEvaluationExpectation( + _BaseEvaluationServiceRestTransport._BaseGetEvaluationExpectation, + EvaluationServiceRestStub, + ): + def __hash__(self): + return hash("EvaluationServiceRestTransport.GetEvaluationExpectation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: evaluation_service.GetEvaluationExpectationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation.EvaluationExpectation: + r"""Call the get evaluation + expectation method over HTTP. + + Args: + request (~.evaluation_service.GetEvaluationExpectationRequest): + The request object. Request message for + [EvaluationService.GetEvaluationExpectation][google.cloud.ces.v1beta.EvaluationService.GetEvaluationExpectation]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.evaluation.EvaluationExpectation: + An evaluation expectation represents + a specific criteria to evaluate against. + + """ + + http_options = _BaseEvaluationServiceRestTransport._BaseGetEvaluationExpectation._get_http_options() + + request, metadata = self._interceptor.pre_get_evaluation_expectation( + request, metadata + ) + transcoded_request = _BaseEvaluationServiceRestTransport._BaseGetEvaluationExpectation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseEvaluationServiceRestTransport._BaseGetEvaluationExpectation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.EvaluationServiceClient.GetEvaluationExpectation", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "GetEvaluationExpectation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + EvaluationServiceRestTransport._GetEvaluationExpectation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = evaluation.EvaluationExpectation() + pb_resp = evaluation.EvaluationExpectation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_evaluation_expectation(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_evaluation_expectation_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = evaluation.EvaluationExpectation.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.EvaluationServiceClient.get_evaluation_expectation", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "GetEvaluationExpectation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetEvaluationResult( + _BaseEvaluationServiceRestTransport._BaseGetEvaluationResult, + EvaluationServiceRestStub, + ): + def __hash__(self): + return hash("EvaluationServiceRestTransport.GetEvaluationResult") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: evaluation_service.GetEvaluationResultRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation.EvaluationResult: + r"""Call the get evaluation result method over HTTP. + + Args: + request (~.evaluation_service.GetEvaluationResultRequest): + The request object. Request message for + [EvaluationService.GetEvaluationResult][google.cloud.ces.v1beta.EvaluationService.GetEvaluationResult]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.evaluation.EvaluationResult: + An evaluation result represents the + output of running an Evaluation. + + """ + + http_options = _BaseEvaluationServiceRestTransport._BaseGetEvaluationResult._get_http_options() + + request, metadata = self._interceptor.pre_get_evaluation_result( + request, metadata + ) + transcoded_request = _BaseEvaluationServiceRestTransport._BaseGetEvaluationResult._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseEvaluationServiceRestTransport._BaseGetEvaluationResult._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.EvaluationServiceClient.GetEvaluationResult", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "GetEvaluationResult", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + EvaluationServiceRestTransport._GetEvaluationResult._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = evaluation.EvaluationResult() + pb_resp = evaluation.EvaluationResult.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_evaluation_result(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_evaluation_result_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = evaluation.EvaluationResult.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.EvaluationServiceClient.get_evaluation_result", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "GetEvaluationResult", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetEvaluationRun( + _BaseEvaluationServiceRestTransport._BaseGetEvaluationRun, + EvaluationServiceRestStub, + ): + def __hash__(self): + return hash("EvaluationServiceRestTransport.GetEvaluationRun") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: evaluation_service.GetEvaluationRunRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation.EvaluationRun: + r"""Call the get evaluation run method over HTTP. + + Args: + request (~.evaluation_service.GetEvaluationRunRequest): + The request object. Request message for + [EvaluationService.GetEvaluationRun][google.cloud.ces.v1beta.EvaluationService.GetEvaluationRun]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.evaluation.EvaluationRun: + An evaluation run represents an all + the evaluation results from an + evaluation execution. + + """ + + http_options = _BaseEvaluationServiceRestTransport._BaseGetEvaluationRun._get_http_options() + + request, metadata = self._interceptor.pre_get_evaluation_run( + request, metadata + ) + transcoded_request = _BaseEvaluationServiceRestTransport._BaseGetEvaluationRun._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseEvaluationServiceRestTransport._BaseGetEvaluationRun._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.EvaluationServiceClient.GetEvaluationRun", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "GetEvaluationRun", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EvaluationServiceRestTransport._GetEvaluationRun._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = evaluation.EvaluationRun() + pb_resp = evaluation.EvaluationRun.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_evaluation_run(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_evaluation_run_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = evaluation.EvaluationRun.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.EvaluationServiceClient.get_evaluation_run", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "GetEvaluationRun", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetScheduledEvaluationRun( + _BaseEvaluationServiceRestTransport._BaseGetScheduledEvaluationRun, + EvaluationServiceRestStub, + ): + def __hash__(self): + return hash("EvaluationServiceRestTransport.GetScheduledEvaluationRun") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: evaluation_service.GetScheduledEvaluationRunRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation.ScheduledEvaluationRun: + r"""Call the get scheduled evaluation + run method over HTTP. + + Args: + request (~.evaluation_service.GetScheduledEvaluationRunRequest): + The request object. Request message for + [EvaluationService.GetScheduledEvaluationRun][google.cloud.ces.v1beta.EvaluationService.GetScheduledEvaluationRun]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.evaluation.ScheduledEvaluationRun: + Represents a scheduled evaluation run + configuration. + + """ + + http_options = _BaseEvaluationServiceRestTransport._BaseGetScheduledEvaluationRun._get_http_options() + + request, metadata = self._interceptor.pre_get_scheduled_evaluation_run( + request, metadata + ) + transcoded_request = _BaseEvaluationServiceRestTransport._BaseGetScheduledEvaluationRun._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseEvaluationServiceRestTransport._BaseGetScheduledEvaluationRun._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.EvaluationServiceClient.GetScheduledEvaluationRun", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "GetScheduledEvaluationRun", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + EvaluationServiceRestTransport._GetScheduledEvaluationRun._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = evaluation.ScheduledEvaluationRun() + pb_resp = evaluation.ScheduledEvaluationRun.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_scheduled_evaluation_run(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_scheduled_evaluation_run_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = evaluation.ScheduledEvaluationRun.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.EvaluationServiceClient.get_scheduled_evaluation_run", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "GetScheduledEvaluationRun", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ImportEvaluations( + _BaseEvaluationServiceRestTransport._BaseImportEvaluations, + EvaluationServiceRestStub, + ): + def __hash__(self): + return hash("EvaluationServiceRestTransport.ImportEvaluations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: evaluation_service.ImportEvaluationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the import evaluations method over HTTP. + + Args: + request (~.evaluation_service.ImportEvaluationsRequest): + The request object. Request message for + [EvaluationService.ImportEvaluations][google.cloud.ces.v1beta.EvaluationService.ImportEvaluations]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseEvaluationServiceRestTransport._BaseImportEvaluations._get_http_options() + + request, metadata = self._interceptor.pre_import_evaluations( + request, metadata + ) + transcoded_request = _BaseEvaluationServiceRestTransport._BaseImportEvaluations._get_transcoded_request( + http_options, request + ) + + body = _BaseEvaluationServiceRestTransport._BaseImportEvaluations._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseEvaluationServiceRestTransport._BaseImportEvaluations._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.EvaluationServiceClient.ImportEvaluations", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "ImportEvaluations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EvaluationServiceRestTransport._ImportEvaluations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_import_evaluations(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_import_evaluations_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.EvaluationServiceClient.import_evaluations", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "ImportEvaluations", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListEvaluationDatasets( + _BaseEvaluationServiceRestTransport._BaseListEvaluationDatasets, + EvaluationServiceRestStub, + ): + def __hash__(self): + return hash("EvaluationServiceRestTransport.ListEvaluationDatasets") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: evaluation_service.ListEvaluationDatasetsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation_service.ListEvaluationDatasetsResponse: + r"""Call the list evaluation datasets method over HTTP. + + Args: + request (~.evaluation_service.ListEvaluationDatasetsRequest): + The request object. Request message for + [EvaluationService.ListEvaluationDatasets][google.cloud.ces.v1beta.EvaluationService.ListEvaluationDatasets]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.evaluation_service.ListEvaluationDatasetsResponse: + Response message for + [EvaluationService.ListEvaluationDatasets][google.cloud.ces.v1beta.EvaluationService.ListEvaluationDatasets]. + + """ + + http_options = _BaseEvaluationServiceRestTransport._BaseListEvaluationDatasets._get_http_options() + + request, metadata = self._interceptor.pre_list_evaluation_datasets( + request, metadata + ) + transcoded_request = _BaseEvaluationServiceRestTransport._BaseListEvaluationDatasets._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseEvaluationServiceRestTransport._BaseListEvaluationDatasets._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.EvaluationServiceClient.ListEvaluationDatasets", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "ListEvaluationDatasets", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + EvaluationServiceRestTransport._ListEvaluationDatasets._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = evaluation_service.ListEvaluationDatasetsResponse() + pb_resp = evaluation_service.ListEvaluationDatasetsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_evaluation_datasets(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_evaluation_datasets_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + evaluation_service.ListEvaluationDatasetsResponse.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.EvaluationServiceClient.list_evaluation_datasets", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "ListEvaluationDatasets", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListEvaluationExpectations( + _BaseEvaluationServiceRestTransport._BaseListEvaluationExpectations, + EvaluationServiceRestStub, + ): + def __hash__(self): + return hash("EvaluationServiceRestTransport.ListEvaluationExpectations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: evaluation_service.ListEvaluationExpectationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation_service.ListEvaluationExpectationsResponse: + r"""Call the list evaluation + expectations method over HTTP. + + Args: + request (~.evaluation_service.ListEvaluationExpectationsRequest): + The request object. Request message for + [EvaluationService.ListEvaluationExpectations][google.cloud.ces.v1beta.EvaluationService.ListEvaluationExpectations]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.evaluation_service.ListEvaluationExpectationsResponse: + Response message for + [EvaluationService.ListEvaluationExpectations][google.cloud.ces.v1beta.EvaluationService.ListEvaluationExpectations]. + + """ + + http_options = _BaseEvaluationServiceRestTransport._BaseListEvaluationExpectations._get_http_options() + + request, metadata = self._interceptor.pre_list_evaluation_expectations( + request, metadata + ) + transcoded_request = _BaseEvaluationServiceRestTransport._BaseListEvaluationExpectations._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseEvaluationServiceRestTransport._BaseListEvaluationExpectations._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.EvaluationServiceClient.ListEvaluationExpectations", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "ListEvaluationExpectations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EvaluationServiceRestTransport._ListEvaluationExpectations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = evaluation_service.ListEvaluationExpectationsResponse() + pb_resp = evaluation_service.ListEvaluationExpectationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_evaluation_expectations(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_evaluation_expectations_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + evaluation_service.ListEvaluationExpectationsResponse.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.EvaluationServiceClient.list_evaluation_expectations", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "ListEvaluationExpectations", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListEvaluationResults( + _BaseEvaluationServiceRestTransport._BaseListEvaluationResults, + EvaluationServiceRestStub, + ): + def __hash__(self): + return hash("EvaluationServiceRestTransport.ListEvaluationResults") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: evaluation_service.ListEvaluationResultsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation_service.ListEvaluationResultsResponse: + r"""Call the list evaluation results method over HTTP. + + Args: + request (~.evaluation_service.ListEvaluationResultsRequest): + The request object. Request message for + [EvaluationService.ListEvaluationResults][google.cloud.ces.v1beta.EvaluationService.ListEvaluationResults]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.evaluation_service.ListEvaluationResultsResponse: + Response message for + [EvaluationService.ListEvaluationResults][google.cloud.ces.v1beta.EvaluationService.ListEvaluationResults]. + + """ + + http_options = _BaseEvaluationServiceRestTransport._BaseListEvaluationResults._get_http_options() + + request, metadata = self._interceptor.pre_list_evaluation_results( + request, metadata + ) + transcoded_request = _BaseEvaluationServiceRestTransport._BaseListEvaluationResults._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseEvaluationServiceRestTransport._BaseListEvaluationResults._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.EvaluationServiceClient.ListEvaluationResults", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "ListEvaluationResults", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + EvaluationServiceRestTransport._ListEvaluationResults._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = evaluation_service.ListEvaluationResultsResponse() + pb_resp = evaluation_service.ListEvaluationResultsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_evaluation_results(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_evaluation_results_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + evaluation_service.ListEvaluationResultsResponse.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.EvaluationServiceClient.list_evaluation_results", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "ListEvaluationResults", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListEvaluationRuns( + _BaseEvaluationServiceRestTransport._BaseListEvaluationRuns, + EvaluationServiceRestStub, + ): + def __hash__(self): + return hash("EvaluationServiceRestTransport.ListEvaluationRuns") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: evaluation_service.ListEvaluationRunsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation_service.ListEvaluationRunsResponse: + r"""Call the list evaluation runs method over HTTP. + + Args: + request (~.evaluation_service.ListEvaluationRunsRequest): + The request object. Request message for + [EvaluationService.ListEvaluationRuns][google.cloud.ces.v1beta.EvaluationService.ListEvaluationRuns]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.evaluation_service.ListEvaluationRunsResponse: + Response message for + [EvaluationService.ListEvaluationRuns][google.cloud.ces.v1beta.EvaluationService.ListEvaluationRuns]. + + """ + + http_options = _BaseEvaluationServiceRestTransport._BaseListEvaluationRuns._get_http_options() + + request, metadata = self._interceptor.pre_list_evaluation_runs( + request, metadata + ) + transcoded_request = _BaseEvaluationServiceRestTransport._BaseListEvaluationRuns._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseEvaluationServiceRestTransport._BaseListEvaluationRuns._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.EvaluationServiceClient.ListEvaluationRuns", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "ListEvaluationRuns", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EvaluationServiceRestTransport._ListEvaluationRuns._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = evaluation_service.ListEvaluationRunsResponse() + pb_resp = evaluation_service.ListEvaluationRunsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_evaluation_runs(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_evaluation_runs_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + evaluation_service.ListEvaluationRunsResponse.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.EvaluationServiceClient.list_evaluation_runs", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "ListEvaluationRuns", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListEvaluations( + _BaseEvaluationServiceRestTransport._BaseListEvaluations, + EvaluationServiceRestStub, + ): + def __hash__(self): + return hash("EvaluationServiceRestTransport.ListEvaluations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: evaluation_service.ListEvaluationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation_service.ListEvaluationsResponse: + r"""Call the list evaluations method over HTTP. + + Args: + request (~.evaluation_service.ListEvaluationsRequest): + The request object. Request message for + [EvaluationService.ListEvaluations][google.cloud.ces.v1beta.EvaluationService.ListEvaluations]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.evaluation_service.ListEvaluationsResponse: + Response message for + [EvaluationService.ListEvaluations][google.cloud.ces.v1beta.EvaluationService.ListEvaluations]. + + """ + + http_options = _BaseEvaluationServiceRestTransport._BaseListEvaluations._get_http_options() + + request, metadata = self._interceptor.pre_list_evaluations( + request, metadata + ) + transcoded_request = _BaseEvaluationServiceRestTransport._BaseListEvaluations._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseEvaluationServiceRestTransport._BaseListEvaluations._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.EvaluationServiceClient.ListEvaluations", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "ListEvaluations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EvaluationServiceRestTransport._ListEvaluations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = evaluation_service.ListEvaluationsResponse() + pb_resp = evaluation_service.ListEvaluationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_evaluations(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_evaluations_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + evaluation_service.ListEvaluationsResponse.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.EvaluationServiceClient.list_evaluations", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "ListEvaluations", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListScheduledEvaluationRuns( + _BaseEvaluationServiceRestTransport._BaseListScheduledEvaluationRuns, + EvaluationServiceRestStub, + ): + def __hash__(self): + return hash("EvaluationServiceRestTransport.ListScheduledEvaluationRuns") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: evaluation_service.ListScheduledEvaluationRunsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation_service.ListScheduledEvaluationRunsResponse: + r"""Call the list scheduled evaluation + runs method over HTTP. + + Args: + request (~.evaluation_service.ListScheduledEvaluationRunsRequest): + The request object. Request message for + [EvaluationService.ListScheduledEvaluationRuns][google.cloud.ces.v1beta.EvaluationService.ListScheduledEvaluationRuns]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.evaluation_service.ListScheduledEvaluationRunsResponse: + Response message for + [EvaluationService.ListScheduledEvaluationRuns][google.cloud.ces.v1beta.EvaluationService.ListScheduledEvaluationRuns]. + + """ + + http_options = _BaseEvaluationServiceRestTransport._BaseListScheduledEvaluationRuns._get_http_options() + + request, metadata = self._interceptor.pre_list_scheduled_evaluation_runs( + request, metadata + ) + transcoded_request = _BaseEvaluationServiceRestTransport._BaseListScheduledEvaluationRuns._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseEvaluationServiceRestTransport._BaseListScheduledEvaluationRuns._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.EvaluationServiceClient.ListScheduledEvaluationRuns", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "ListScheduledEvaluationRuns", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EvaluationServiceRestTransport._ListScheduledEvaluationRuns._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = evaluation_service.ListScheduledEvaluationRunsResponse() + pb_resp = evaluation_service.ListScheduledEvaluationRunsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_scheduled_evaluation_runs(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_list_scheduled_evaluation_runs_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + evaluation_service.ListScheduledEvaluationRunsResponse.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.EvaluationServiceClient.list_scheduled_evaluation_runs", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "ListScheduledEvaluationRuns", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _RunEvaluation( + _BaseEvaluationServiceRestTransport._BaseRunEvaluation, + EvaluationServiceRestStub, + ): + def __hash__(self): + return hash("EvaluationServiceRestTransport.RunEvaluation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: evaluation.RunEvaluationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the run evaluation method over HTTP. + + Args: + request (~.evaluation.RunEvaluationRequest): + The request object. Request message for + [EvaluationService.RunEvaluation][google.cloud.ces.v1beta.EvaluationService.RunEvaluation]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseEvaluationServiceRestTransport._BaseRunEvaluation._get_http_options() + + request, metadata = self._interceptor.pre_run_evaluation(request, metadata) + transcoded_request = _BaseEvaluationServiceRestTransport._BaseRunEvaluation._get_transcoded_request( + http_options, request + ) + + body = _BaseEvaluationServiceRestTransport._BaseRunEvaluation._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseEvaluationServiceRestTransport._BaseRunEvaluation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.EvaluationServiceClient.RunEvaluation", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "RunEvaluation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EvaluationServiceRestTransport._RunEvaluation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_run_evaluation(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_run_evaluation_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.EvaluationServiceClient.run_evaluation", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "RunEvaluation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _TestPersonaVoice( + _BaseEvaluationServiceRestTransport._BaseTestPersonaVoice, + EvaluationServiceRestStub, + ): + def __hash__(self): + return hash("EvaluationServiceRestTransport.TestPersonaVoice") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: evaluation_service.TestPersonaVoiceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation_service.TestPersonaVoiceResponse: + r"""Call the test persona voice method over HTTP. + + Args: + request (~.evaluation_service.TestPersonaVoiceRequest): + The request object. Request message for + [EvaluationService.TestPersonaVoice][google.cloud.ces.v1beta.EvaluationService.TestPersonaVoice]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.evaluation_service.TestPersonaVoiceResponse: + Response message for + [EvaluationService.TestPersonaVoice][google.cloud.ces.v1beta.EvaluationService.TestPersonaVoice]. + + """ + + http_options = _BaseEvaluationServiceRestTransport._BaseTestPersonaVoice._get_http_options() + + request, metadata = self._interceptor.pre_test_persona_voice( + request, metadata + ) + transcoded_request = _BaseEvaluationServiceRestTransport._BaseTestPersonaVoice._get_transcoded_request( + http_options, request + ) + + body = _BaseEvaluationServiceRestTransport._BaseTestPersonaVoice._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseEvaluationServiceRestTransport._BaseTestPersonaVoice._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.EvaluationServiceClient.TestPersonaVoice", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "TestPersonaVoice", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EvaluationServiceRestTransport._TestPersonaVoice._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = evaluation_service.TestPersonaVoiceResponse() + pb_resp = evaluation_service.TestPersonaVoiceResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_test_persona_voice(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_test_persona_voice_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + evaluation_service.TestPersonaVoiceResponse.to_json(response) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.EvaluationServiceClient.test_persona_voice", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "TestPersonaVoice", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateEvaluation( + _BaseEvaluationServiceRestTransport._BaseUpdateEvaluation, + EvaluationServiceRestStub, + ): + def __hash__(self): + return hash("EvaluationServiceRestTransport.UpdateEvaluation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: evaluation_service.UpdateEvaluationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcc_evaluation.Evaluation: + r"""Call the update evaluation method over HTTP. + + Args: + request (~.evaluation_service.UpdateEvaluationRequest): + The request object. Request message for + [EvaluationService.UpdateEvaluation][google.cloud.ces.v1beta.EvaluationService.UpdateEvaluation]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gcc_evaluation.Evaluation: + An evaluation represents all of the + information needed to simulate and + evaluate an agent. + + """ + + http_options = _BaseEvaluationServiceRestTransport._BaseUpdateEvaluation._get_http_options() + + request, metadata = self._interceptor.pre_update_evaluation( + request, metadata + ) + transcoded_request = _BaseEvaluationServiceRestTransport._BaseUpdateEvaluation._get_transcoded_request( + http_options, request + ) + + body = _BaseEvaluationServiceRestTransport._BaseUpdateEvaluation._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseEvaluationServiceRestTransport._BaseUpdateEvaluation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.EvaluationServiceClient.UpdateEvaluation", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "UpdateEvaluation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EvaluationServiceRestTransport._UpdateEvaluation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gcc_evaluation.Evaluation() + pb_resp = gcc_evaluation.Evaluation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_evaluation(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_evaluation_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gcc_evaluation.Evaluation.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.EvaluationServiceClient.update_evaluation", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "UpdateEvaluation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateEvaluationDataset( + _BaseEvaluationServiceRestTransport._BaseUpdateEvaluationDataset, + EvaluationServiceRestStub, + ): + def __hash__(self): + return hash("EvaluationServiceRestTransport.UpdateEvaluationDataset") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: evaluation_service.UpdateEvaluationDatasetRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation.EvaluationDataset: + r"""Call the update evaluation dataset method over HTTP. + + Args: + request (~.evaluation_service.UpdateEvaluationDatasetRequest): + The request object. Request message for + [EvaluationService.UpdateEvaluationDataset][google.cloud.ces.v1beta.EvaluationService.UpdateEvaluationDataset]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.evaluation.EvaluationDataset: + An evaluation dataset represents a + set of evaluations that are grouped + together basaed on shared tags. + + """ + + http_options = _BaseEvaluationServiceRestTransport._BaseUpdateEvaluationDataset._get_http_options() + + request, metadata = self._interceptor.pre_update_evaluation_dataset( + request, metadata + ) + transcoded_request = _BaseEvaluationServiceRestTransport._BaseUpdateEvaluationDataset._get_transcoded_request( + http_options, request + ) + + body = _BaseEvaluationServiceRestTransport._BaseUpdateEvaluationDataset._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseEvaluationServiceRestTransport._BaseUpdateEvaluationDataset._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.EvaluationServiceClient.UpdateEvaluationDataset", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "UpdateEvaluationDataset", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + EvaluationServiceRestTransport._UpdateEvaluationDataset._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = evaluation.EvaluationDataset() + pb_resp = evaluation.EvaluationDataset.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_evaluation_dataset(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_evaluation_dataset_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = evaluation.EvaluationDataset.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.EvaluationServiceClient.update_evaluation_dataset", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "UpdateEvaluationDataset", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateEvaluationExpectation( + _BaseEvaluationServiceRestTransport._BaseUpdateEvaluationExpectation, + EvaluationServiceRestStub, + ): + def __hash__(self): + return hash("EvaluationServiceRestTransport.UpdateEvaluationExpectation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: evaluation_service.UpdateEvaluationExpectationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation.EvaluationExpectation: + r"""Call the update evaluation + expectation method over HTTP. + + Args: + request (~.evaluation_service.UpdateEvaluationExpectationRequest): + The request object. Request message for + [EvaluationService.UpdateEvaluationExpectation][google.cloud.ces.v1beta.EvaluationService.UpdateEvaluationExpectation]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.evaluation.EvaluationExpectation: + An evaluation expectation represents + a specific criteria to evaluate against. + + """ + + http_options = _BaseEvaluationServiceRestTransport._BaseUpdateEvaluationExpectation._get_http_options() + + request, metadata = self._interceptor.pre_update_evaluation_expectation( + request, metadata + ) + transcoded_request = _BaseEvaluationServiceRestTransport._BaseUpdateEvaluationExpectation._get_transcoded_request( + http_options, request + ) + + body = _BaseEvaluationServiceRestTransport._BaseUpdateEvaluationExpectation._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseEvaluationServiceRestTransport._BaseUpdateEvaluationExpectation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.EvaluationServiceClient.UpdateEvaluationExpectation", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "UpdateEvaluationExpectation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EvaluationServiceRestTransport._UpdateEvaluationExpectation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = evaluation.EvaluationExpectation() + pb_resp = evaluation.EvaluationExpectation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_evaluation_expectation(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_update_evaluation_expectation_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = evaluation.EvaluationExpectation.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.EvaluationServiceClient.update_evaluation_expectation", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "UpdateEvaluationExpectation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateScheduledEvaluationRun( + _BaseEvaluationServiceRestTransport._BaseUpdateScheduledEvaluationRun, + EvaluationServiceRestStub, + ): + def __hash__(self): + return hash("EvaluationServiceRestTransport.UpdateScheduledEvaluationRun") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: evaluation_service.UpdateScheduledEvaluationRunRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation.ScheduledEvaluationRun: + r"""Call the update scheduled + evaluation run method over HTTP. + + Args: + request (~.evaluation_service.UpdateScheduledEvaluationRunRequest): + The request object. Request message for + [EvaluationService.UpdateScheduledEvaluationRun][google.cloud.ces.v1beta.EvaluationService.UpdateScheduledEvaluationRun]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.evaluation.ScheduledEvaluationRun: + Represents a scheduled evaluation run + configuration. + + """ + + http_options = _BaseEvaluationServiceRestTransport._BaseUpdateScheduledEvaluationRun._get_http_options() + + request, metadata = self._interceptor.pre_update_scheduled_evaluation_run( + request, metadata + ) + transcoded_request = _BaseEvaluationServiceRestTransport._BaseUpdateScheduledEvaluationRun._get_transcoded_request( + http_options, request + ) + + body = _BaseEvaluationServiceRestTransport._BaseUpdateScheduledEvaluationRun._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseEvaluationServiceRestTransport._BaseUpdateScheduledEvaluationRun._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.EvaluationServiceClient.UpdateScheduledEvaluationRun", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "UpdateScheduledEvaluationRun", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EvaluationServiceRestTransport._UpdateScheduledEvaluationRun._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = evaluation.ScheduledEvaluationRun() + pb_resp = evaluation.ScheduledEvaluationRun.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_scheduled_evaluation_run(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_update_scheduled_evaluation_run_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = evaluation.ScheduledEvaluationRun.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.EvaluationServiceClient.update_scheduled_evaluation_run", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "UpdateScheduledEvaluationRun", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UploadEvaluationAudio( + _BaseEvaluationServiceRestTransport._BaseUploadEvaluationAudio, + EvaluationServiceRestStub, + ): + def __hash__(self): + return hash("EvaluationServiceRestTransport.UploadEvaluationAudio") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: evaluation_service.UploadEvaluationAudioRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> evaluation_service.UploadEvaluationAudioResponse: + r"""Call the upload evaluation audio method over HTTP. + + Args: + request (~.evaluation_service.UploadEvaluationAudioRequest): + The request object. Request message for + [EvaluationService.UploadEvaluationAudio][google.cloud.ces.v1beta.EvaluationService.UploadEvaluationAudio]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.evaluation_service.UploadEvaluationAudioResponse: + Response message for + [EvaluationService.UploadEvaluationAudio][google.cloud.ces.v1beta.EvaluationService.UploadEvaluationAudio]. + + """ + + http_options = _BaseEvaluationServiceRestTransport._BaseUploadEvaluationAudio._get_http_options() + + request, metadata = self._interceptor.pre_upload_evaluation_audio( + request, metadata + ) + transcoded_request = _BaseEvaluationServiceRestTransport._BaseUploadEvaluationAudio._get_transcoded_request( + http_options, request + ) + + body = _BaseEvaluationServiceRestTransport._BaseUploadEvaluationAudio._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseEvaluationServiceRestTransport._BaseUploadEvaluationAudio._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.EvaluationServiceClient.UploadEvaluationAudio", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "UploadEvaluationAudio", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + EvaluationServiceRestTransport._UploadEvaluationAudio._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = evaluation_service.UploadEvaluationAudioResponse() + pb_resp = evaluation_service.UploadEvaluationAudioResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_upload_evaluation_audio(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_upload_evaluation_audio_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + evaluation_service.UploadEvaluationAudioResponse.to_json( + response + ) + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.EvaluationServiceClient.upload_evaluation_audio", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "UploadEvaluationAudio", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_evaluation( + self, + ) -> Callable[ + [evaluation_service.CreateEvaluationRequest], gcc_evaluation.Evaluation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateEvaluation(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_evaluation_dataset( + self, + ) -> Callable[ + [evaluation_service.CreateEvaluationDatasetRequest], + evaluation.EvaluationDataset, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateEvaluationDataset( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def create_evaluation_expectation( + self, + ) -> Callable[ + [evaluation_service.CreateEvaluationExpectationRequest], + evaluation.EvaluationExpectation, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateEvaluationExpectation( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def create_scheduled_evaluation_run( + self, + ) -> Callable[ + [evaluation_service.CreateScheduledEvaluationRunRequest], + evaluation.ScheduledEvaluationRun, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateScheduledEvaluationRun( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def delete_evaluation( + self, + ) -> Callable[[evaluation_service.DeleteEvaluationRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteEvaluation(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_evaluation_dataset( + self, + ) -> Callable[[evaluation_service.DeleteEvaluationDatasetRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteEvaluationDataset( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def delete_evaluation_expectation( + self, + ) -> Callable[ + [evaluation_service.DeleteEvaluationExpectationRequest], empty_pb2.Empty + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteEvaluationExpectation( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def delete_evaluation_result( + self, + ) -> Callable[[evaluation_service.DeleteEvaluationResultRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteEvaluationResult( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def delete_evaluation_run( + self, + ) -> Callable[ + [evaluation_service.DeleteEvaluationRunRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteEvaluationRun(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_scheduled_evaluation_run( + self, + ) -> Callable[ + [evaluation_service.DeleteScheduledEvaluationRunRequest], empty_pb2.Empty + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteScheduledEvaluationRun( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def generate_evaluation( + self, + ) -> Callable[ + [evaluation_service.GenerateEvaluationRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GenerateEvaluation(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_evaluation( + self, + ) -> Callable[[evaluation_service.GetEvaluationRequest], evaluation.Evaluation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetEvaluation(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_evaluation_dataset( + self, + ) -> Callable[ + [evaluation_service.GetEvaluationDatasetRequest], evaluation.EvaluationDataset + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetEvaluationDataset(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_evaluation_expectation( + self, + ) -> Callable[ + [evaluation_service.GetEvaluationExpectationRequest], + evaluation.EvaluationExpectation, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetEvaluationExpectation( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def get_evaluation_result( + self, + ) -> Callable[ + [evaluation_service.GetEvaluationResultRequest], evaluation.EvaluationResult + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetEvaluationResult(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_evaluation_run( + self, + ) -> Callable[ + [evaluation_service.GetEvaluationRunRequest], evaluation.EvaluationRun + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetEvaluationRun(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_scheduled_evaluation_run( + self, + ) -> Callable[ + [evaluation_service.GetScheduledEvaluationRunRequest], + evaluation.ScheduledEvaluationRun, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetScheduledEvaluationRun( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def import_evaluations( + self, + ) -> Callable[ + [evaluation_service.ImportEvaluationsRequest], operations_pb2.Operation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ImportEvaluations(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_evaluation_datasets( + self, + ) -> Callable[ + [evaluation_service.ListEvaluationDatasetsRequest], + evaluation_service.ListEvaluationDatasetsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListEvaluationDatasets( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def list_evaluation_expectations( + self, + ) -> Callable[ + [evaluation_service.ListEvaluationExpectationsRequest], + evaluation_service.ListEvaluationExpectationsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListEvaluationExpectations( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def list_evaluation_results( + self, + ) -> Callable[ + [evaluation_service.ListEvaluationResultsRequest], + evaluation_service.ListEvaluationResultsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListEvaluationResults(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_evaluation_runs( + self, + ) -> Callable[ + [evaluation_service.ListEvaluationRunsRequest], + evaluation_service.ListEvaluationRunsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListEvaluationRuns(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_evaluations( + self, + ) -> Callable[ + [evaluation_service.ListEvaluationsRequest], + evaluation_service.ListEvaluationsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListEvaluations(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_scheduled_evaluation_runs( + self, + ) -> Callable[ + [evaluation_service.ListScheduledEvaluationRunsRequest], + evaluation_service.ListScheduledEvaluationRunsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListScheduledEvaluationRuns( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def run_evaluation( + self, + ) -> Callable[[evaluation.RunEvaluationRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RunEvaluation(self._session, self._host, self._interceptor) # type: ignore + + @property + def test_persona_voice( + self, + ) -> Callable[ + [evaluation_service.TestPersonaVoiceRequest], + evaluation_service.TestPersonaVoiceResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._TestPersonaVoice(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_evaluation( + self, + ) -> Callable[ + [evaluation_service.UpdateEvaluationRequest], gcc_evaluation.Evaluation + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateEvaluation(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_evaluation_dataset( + self, + ) -> Callable[ + [evaluation_service.UpdateEvaluationDatasetRequest], + evaluation.EvaluationDataset, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateEvaluationDataset( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def update_evaluation_expectation( + self, + ) -> Callable[ + [evaluation_service.UpdateEvaluationExpectationRequest], + evaluation.EvaluationExpectation, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateEvaluationExpectation( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def update_scheduled_evaluation_run( + self, + ) -> Callable[ + [evaluation_service.UpdateScheduledEvaluationRunRequest], + evaluation.ScheduledEvaluationRun, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateScheduledEvaluationRun( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def upload_evaluation_audio( + self, + ) -> Callable[ + [evaluation_service.UploadEvaluationAudioRequest], + evaluation_service.UploadEvaluationAudioResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UploadEvaluationAudio(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation( + _BaseEvaluationServiceRestTransport._BaseGetLocation, EvaluationServiceRestStub + ): + def __hash__(self): + return hash("EvaluationServiceRestTransport.GetLocation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: locations_pb2.GetLocationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options = ( + _BaseEvaluationServiceRestTransport._BaseGetLocation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_location(request, metadata) + transcoded_request = _BaseEvaluationServiceRestTransport._BaseGetLocation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseEvaluationServiceRestTransport._BaseGetLocation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.EvaluationServiceClient.GetLocation", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "GetLocation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EvaluationServiceRestTransport._GetLocation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.Location() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_location(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.EvaluationServiceAsyncClient.GetLocation", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "GetLocation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations( + _BaseEvaluationServiceRestTransport._BaseListLocations, + EvaluationServiceRestStub, + ): + def __hash__(self): + return hash("EvaluationServiceRestTransport.ListLocations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: locations_pb2.ListLocationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options = _BaseEvaluationServiceRestTransport._BaseListLocations._get_http_options() + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + transcoded_request = _BaseEvaluationServiceRestTransport._BaseListLocations._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseEvaluationServiceRestTransport._BaseListLocations._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.EvaluationServiceClient.ListLocations", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "ListLocations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EvaluationServiceRestTransport._ListLocations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_locations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.EvaluationServiceAsyncClient.ListLocations", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "ListLocations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation( + _BaseEvaluationServiceRestTransport._BaseCancelOperation, + EvaluationServiceRestStub, + ): + def __hash__(self): + return hash("EvaluationServiceRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseEvaluationServiceRestTransport._BaseCancelOperation._get_http_options() + + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + transcoded_request = _BaseEvaluationServiceRestTransport._BaseCancelOperation._get_transcoded_request( + http_options, request + ) + + body = _BaseEvaluationServiceRestTransport._BaseCancelOperation._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseEvaluationServiceRestTransport._BaseCancelOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.EvaluationServiceClient.CancelOperation", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EvaluationServiceRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation( + _BaseEvaluationServiceRestTransport._BaseDeleteOperation, + EvaluationServiceRestStub, + ): + def __hash__(self): + return hash("EvaluationServiceRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.DeleteOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseEvaluationServiceRestTransport._BaseDeleteOperation._get_http_options() + + request, metadata = self._interceptor.pre_delete_operation( + request, metadata + ) + transcoded_request = _BaseEvaluationServiceRestTransport._BaseDeleteOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseEvaluationServiceRestTransport._BaseDeleteOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.EvaluationServiceClient.DeleteOperation", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "DeleteOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EvaluationServiceRestTransport._DeleteOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation( + _BaseEvaluationServiceRestTransport._BaseGetOperation, EvaluationServiceRestStub + ): + def __hash__(self): + return hash("EvaluationServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = _BaseEvaluationServiceRestTransport._BaseGetOperation._get_http_options() + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseEvaluationServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseEvaluationServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.EvaluationServiceClient.GetOperation", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EvaluationServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.EvaluationServiceAsyncClient.GetOperation", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations( + _BaseEvaluationServiceRestTransport._BaseListOperations, + EvaluationServiceRestStub, + ): + def __hash__(self): + return hash("EvaluationServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options = _BaseEvaluationServiceRestTransport._BaseListOperations._get_http_options() + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = _BaseEvaluationServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseEvaluationServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.EvaluationServiceClient.ListOperations", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = EvaluationServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.EvaluationServiceAsyncClient.ListOperations", + extra={ + "serviceName": "google.cloud.ces.v1beta.EvaluationService", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("EvaluationServiceRestTransport",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/transports/rest_base.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/transports/rest_base.py new file mode 100644 index 000000000000..65f9e6f7d1ff --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/evaluation_service/transports/rest_base.py @@ -0,0 +1,1854 @@ +# -*- coding: utf-8 -*- +# 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. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.ces_v1beta.types import evaluation, evaluation_service +from google.cloud.ces_v1beta.types import evaluation as gcc_evaluation + +from .base import DEFAULT_CLIENT_INFO, EvaluationServiceTransport + + +class _BaseEvaluationServiceRestTransport(EvaluationServiceTransport): + """Base REST backend transport for EvaluationService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "ces.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'ces.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseCreateEvaluation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*/apps/*}/evaluations", + "body": "evaluation", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = evaluation_service.CreateEvaluationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseEvaluationServiceRestTransport._BaseCreateEvaluation._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateEvaluationDataset: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*/apps/*}/evaluationDatasets", + "body": "evaluation_dataset", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = evaluation_service.CreateEvaluationDatasetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseEvaluationServiceRestTransport._BaseCreateEvaluationDataset._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateEvaluationExpectation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*/apps/*}/evaluationExpectations", + "body": "evaluation_expectation", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = evaluation_service.CreateEvaluationExpectationRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseEvaluationServiceRestTransport._BaseCreateEvaluationExpectation._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateScheduledEvaluationRun: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*/apps/*}/scheduledEvaluationRuns", + "body": "scheduled_evaluation_run", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = evaluation_service.CreateScheduledEvaluationRunRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseEvaluationServiceRestTransport._BaseCreateScheduledEvaluationRun._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteEvaluation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/apps/*/evaluations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = evaluation_service.DeleteEvaluationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseEvaluationServiceRestTransport._BaseDeleteEvaluation._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteEvaluationDataset: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/apps/*/evaluationDatasets/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = evaluation_service.DeleteEvaluationDatasetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseEvaluationServiceRestTransport._BaseDeleteEvaluationDataset._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteEvaluationExpectation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/apps/*/evaluationExpectations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = evaluation_service.DeleteEvaluationExpectationRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseEvaluationServiceRestTransport._BaseDeleteEvaluationExpectation._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteEvaluationResult: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/apps/*/evaluations/*/results/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = evaluation_service.DeleteEvaluationResultRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseEvaluationServiceRestTransport._BaseDeleteEvaluationResult._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteEvaluationRun: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/apps/*/evaluationRuns/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = evaluation_service.DeleteEvaluationRunRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseEvaluationServiceRestTransport._BaseDeleteEvaluationRun._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteScheduledEvaluationRun: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/apps/*/scheduledEvaluationRuns/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = evaluation_service.DeleteScheduledEvaluationRunRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseEvaluationServiceRestTransport._BaseDeleteScheduledEvaluationRun._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGenerateEvaluation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{conversation=projects/*/locations/*/apps/*/conversations/*}:generateEvaluation", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = evaluation_service.GenerateEvaluationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseEvaluationServiceRestTransport._BaseGenerateEvaluation._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetEvaluation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/apps/*/evaluations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = evaluation_service.GetEvaluationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseEvaluationServiceRestTransport._BaseGetEvaluation._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetEvaluationDataset: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/apps/*/evaluationDatasets/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = evaluation_service.GetEvaluationDatasetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseEvaluationServiceRestTransport._BaseGetEvaluationDataset._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetEvaluationExpectation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/apps/*/evaluationExpectations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = evaluation_service.GetEvaluationExpectationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseEvaluationServiceRestTransport._BaseGetEvaluationExpectation._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetEvaluationResult: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/apps/*/evaluations/*/results/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = evaluation_service.GetEvaluationResultRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseEvaluationServiceRestTransport._BaseGetEvaluationResult._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetEvaluationRun: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/apps/*/evaluationRuns/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = evaluation_service.GetEvaluationRunRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseEvaluationServiceRestTransport._BaseGetEvaluationRun._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetScheduledEvaluationRun: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/apps/*/scheduledEvaluationRuns/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = evaluation_service.GetScheduledEvaluationRunRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseEvaluationServiceRestTransport._BaseGetScheduledEvaluationRun._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseImportEvaluations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*/apps/*}:importEvaluations", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = evaluation_service.ImportEvaluationsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseEvaluationServiceRestTransport._BaseImportEvaluations._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListEvaluationDatasets: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*/apps/*}/evaluationDatasets", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = evaluation_service.ListEvaluationDatasetsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseEvaluationServiceRestTransport._BaseListEvaluationDatasets._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListEvaluationExpectations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*/apps/*}/evaluationExpectations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = evaluation_service.ListEvaluationExpectationsRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseEvaluationServiceRestTransport._BaseListEvaluationExpectations._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListEvaluationResults: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*/apps/*/evaluations/*}/results", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = evaluation_service.ListEvaluationResultsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseEvaluationServiceRestTransport._BaseListEvaluationResults._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListEvaluationRuns: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*/apps/*}/evaluationRuns", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = evaluation_service.ListEvaluationRunsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseEvaluationServiceRestTransport._BaseListEvaluationRuns._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListEvaluations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*/apps/*}/evaluations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = evaluation_service.ListEvaluationsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseEvaluationServiceRestTransport._BaseListEvaluations._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListScheduledEvaluationRuns: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*/apps/*}/scheduledEvaluationRuns", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = evaluation_service.ListScheduledEvaluationRunsRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseEvaluationServiceRestTransport._BaseListScheduledEvaluationRuns._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRunEvaluation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{app=projects/*/locations/*/apps/*}:runEvaluation", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = evaluation.RunEvaluationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseEvaluationServiceRestTransport._BaseRunEvaluation._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseTestPersonaVoice: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{app=projects/*/locations/*/apps/*}:testPersonaVoice", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = evaluation_service.TestPersonaVoiceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseEvaluationServiceRestTransport._BaseTestPersonaVoice._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateEvaluation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta/{evaluation.name=projects/*/locations/*/apps/*/evaluations/*}", + "body": "evaluation", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = evaluation_service.UpdateEvaluationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseEvaluationServiceRestTransport._BaseUpdateEvaluation._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateEvaluationDataset: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta/{evaluation_dataset.name=projects/*/locations/*/apps/*/evaluationDatasets/*}", + "body": "evaluation_dataset", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = evaluation_service.UpdateEvaluationDatasetRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseEvaluationServiceRestTransport._BaseUpdateEvaluationDataset._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateEvaluationExpectation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta/{evaluation_expectation.name=projects/*/locations/*/apps/*/evaluationExpectations/*}", + "body": "evaluation_expectation", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = evaluation_service.UpdateEvaluationExpectationRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseEvaluationServiceRestTransport._BaseUpdateEvaluationExpectation._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateScheduledEvaluationRun: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta/{scheduled_evaluation_run.name=projects/*/locations/*/apps/*/scheduledEvaluationRuns/*}", + "body": "scheduled_evaluation_run", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = evaluation_service.UpdateScheduledEvaluationRunRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseEvaluationServiceRestTransport._BaseUpdateScheduledEvaluationRun._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUploadEvaluationAudio: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{app=projects/*/locations/*/apps/*}:uploadEvaluationAudio", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = evaluation_service.UploadEvaluationAudioRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseEvaluationServiceRestTransport._BaseUploadEvaluationAudio._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetLocation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListLocations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*}/locations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseEvaluationServiceRestTransport",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/__init__.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/__init__.py new file mode 100644 index 000000000000..c278fb1603a2 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# 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 .async_client import SessionServiceAsyncClient +from .client import SessionServiceClient + +__all__ = ( + "SessionServiceClient", + "SessionServiceAsyncClient", +) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/async_client.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/async_client.py new file mode 100644 index 000000000000..6c3981393c15 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/async_client.py @@ -0,0 +1,904 @@ +# -*- coding: utf-8 -*- +# 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. +# +import logging as std_logging +import re +from collections import OrderedDict +from typing import ( + AsyncIterable, + AsyncIterator, + Awaitable, + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.ces_v1beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.ces_v1beta.types import session_service + +from .client import SessionServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, SessionServiceTransport +from .transports.grpc_asyncio import SessionServiceGrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class SessionServiceAsyncClient: + """Session service provides APIs for interacting with CES + agents. + """ + + _client: SessionServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = SessionServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SessionServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = SessionServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = SessionServiceClient._DEFAULT_UNIVERSE + + agent_path = staticmethod(SessionServiceClient.agent_path) + parse_agent_path = staticmethod(SessionServiceClient.parse_agent_path) + session_path = staticmethod(SessionServiceClient.session_path) + parse_session_path = staticmethod(SessionServiceClient.parse_session_path) + tool_path = staticmethod(SessionServiceClient.tool_path) + parse_tool_path = staticmethod(SessionServiceClient.parse_tool_path) + toolset_path = staticmethod(SessionServiceClient.toolset_path) + parse_toolset_path = staticmethod(SessionServiceClient.parse_toolset_path) + common_billing_account_path = staticmethod( + SessionServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + SessionServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(SessionServiceClient.common_folder_path) + parse_common_folder_path = staticmethod( + SessionServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + SessionServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + SessionServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod(SessionServiceClient.common_project_path) + parse_common_project_path = staticmethod( + SessionServiceClient.parse_common_project_path + ) + common_location_path = staticmethod(SessionServiceClient.common_location_path) + parse_common_location_path = staticmethod( + SessionServiceClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SessionServiceAsyncClient: The constructed client. + """ + sa_info_func = ( + SessionServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(SessionServiceAsyncClient, info, *args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SessionServiceAsyncClient: The constructed client. + """ + sa_file_func = ( + SessionServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(SessionServiceAsyncClient, filename, *args, **kwargs) + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return SessionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> SessionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SessionServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = SessionServiceClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, SessionServiceTransport, Callable[..., SessionServiceTransport]] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the session service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,SessionServiceTransport,Callable[..., SessionServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the SessionServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = SessionServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.ces_v1beta.SessionServiceAsyncClient`.", + extra={ + "serviceName": "google.cloud.ces.v1beta.SessionService", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.cloud.ces.v1beta.SessionService", + "credentialsType": None, + }, + ) + + async def run_session( + self, + request: Optional[Union[session_service.RunSessionRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> session_service.RunSessionResponse: + r"""Initiates a single turn interaction with the CES + agent within a session. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_run_session(): + # Create a client + client = ces_v1beta.SessionServiceAsyncClient() + + # Initialize request argument(s) + config = ces_v1beta.SessionConfig() + config.session = "session_value" + + inputs = ces_v1beta.SessionInput() + inputs.text = "text_value" + + request = ces_v1beta.RunSessionRequest( + config=config, + inputs=inputs, + ) + + # Make the request + response = await client.run_session(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.RunSessionRequest, dict]]): + The request object. Request message for + [SessionService.RunSession][google.cloud.ces.v1beta.SessionService.RunSession]. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.RunSessionResponse: + Response message for + [SessionService.RunSession][google.cloud.ces.v1beta.SessionService.RunSession]. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, session_service.RunSessionRequest): + request = session_service.RunSessionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.run_session + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("config.session", request.config.session),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def bidi_run_session( + self, + requests: Optional[ + AsyncIterator[session_service.BidiSessionClientMessage] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> Awaitable[AsyncIterable[session_service.BidiSessionServerMessage]]: + r"""Establishes a bidirectional streaming connection with the CES + agent. The agent processes continuous multimodal inputs (e.g., + text, audio) and generates real-time multimodal output streams. + + --- Client Request Stream --- The client streams requests in the + following order: + + 1. Initialization: The first message must contain + [SessionConfig][google.cloud.ces.v1beta.BidiSessionClientMessage.config]. + For audio sessions, this should also include + [InputAudioConfig][google.cloud.ces.v1beta.SessionConfig.input_audio_config] + and + [OutputAudioConfig][google.cloud.ces.v1beta.SessionConfig.output_audio_config] + to define audio processing and synthesis parameters. + + 2. Interaction: Subsequent messages stream + [SessionInput][google.cloud.ces.v1beta.BidiSessionClientMessage.realtime_input] + containing real-time user input data. + + 3. Termination: The client should half-close the stream when + there is no more user input. It should also half-close upon + receiving + [EndSession][google.cloud.ces.v1beta.BidiSessionServerMessage.end_session] + or + [GoAway][google.cloud.ces.v1beta.BidiSessionServerMessage.go_away] + from the agent. + + --- Server Response Stream --- For each interaction turn, the + agent streams messages in the following sequence: + + 1. Speech Recognition (First N messages): Contains + [RecognitionResult][google.cloud.ces.v1beta.BidiSessionServerMessage.recognition_result] + representing the concatenated user speech segments captured + so far. This is only populated for audio sessions. + + 2. Response (Next M messages): Contains + [SessionOutput][google.cloud.ces.v1beta.BidiSessionServerMessage.session_output] + delivering the agent's response in various modalities (e.g., + text, audio). + + 3. Turn Completion (Final message of the turn): Contains + [SessionOutput][google.cloud.ces.v1beta.BidiSessionServerMessage.session_output] + with + [turn_completed][google.cloud.ces.v1beta.SessionOutput.turn_completed] + set to true. This signals the end of the current turn and + includes + [DiagnosticInfo][google.cloud.ces.v1beta.SessionOutput.diagnostic_info] + with execution details. + + --- Audio Best Practices --- + + 1. Streaming: Stream [audio + data][google.cloud.ces.v1beta.SessionInput.audio] + **CONTINUOUSLY**, even during silence. Recommended chunk + size: 40-120ms (balances latency vs. efficiency). + + 2. Playback & Interruption: Play [audio + responses][google.cloud.ces.v1beta.SessionOutput.audio] upon + receipt. Stop playback immediately if an + [InterruptionSignal][google.cloud.ces.v1beta.BidiSessionServerMessage.interruption_signal] + is received (e.g., user barge-in or new agent response). + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_bidi_run_session(): + # Create a client + client = ces_v1beta.SessionServiceAsyncClient() + + # Initialize request argument(s) + config = ces_v1beta.SessionConfig() + config.session = "session_value" + + request = ces_v1beta.BidiSessionClientMessage( + config=config, + ) + + # This method expects an iterator which contains + # 'ces_v1beta.BidiSessionClientMessage' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = await client.bidi_run_session(requests=request_generator()) + + # Handle the response + async for response in stream: + print(response) + + Args: + requests (AsyncIterator[`google.cloud.ces_v1beta.types.BidiSessionClientMessage`]): + The request object AsyncIterator. The top-level message sent by the client for the + [SessionService.BidiRunSession][google.cloud.ces.v1beta.SessionService.BidiRunSession] + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + AsyncIterable[google.cloud.ces_v1beta.types.BidiSessionServerMessage]: + The top-level message returned from + [SessionService.BidiRunSession][google.cloud.ces.v1beta.SessionService.BidiRunSession] + method. + + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.bidi_run_session + ] + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.delete_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "SessionServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("SessionServiceAsyncClient",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/client.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/client.py new file mode 100644 index 000000000000..5ff1797ce43e --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/client.py @@ -0,0 +1,1419 @@ +# -*- coding: utf-8 -*- +# 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. +# +import json +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Iterable, + Iterator, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.ces_v1beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.ces_v1beta.types import session_service + +from .transports.base import DEFAULT_CLIENT_INFO, SessionServiceTransport +from .transports.grpc import SessionServiceGrpcTransport +from .transports.grpc_asyncio import SessionServiceGrpcAsyncIOTransport +from .transports.rest import SessionServiceRestTransport + + +class SessionServiceClientMeta(type): + """Metaclass for the SessionService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[SessionServiceTransport]] + _transport_registry["grpc"] = SessionServiceGrpcTransport + _transport_registry["grpc_asyncio"] = SessionServiceGrpcAsyncIOTransport + _transport_registry["rest"] = SessionServiceRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[SessionServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class SessionServiceClient(metaclass=SessionServiceClientMeta): + """Session service provides APIs for interacting with CES + agents. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "ces.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "ces.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SessionServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SessionServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> SessionServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SessionServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def agent_path( + project: str, + location: str, + app: str, + agent: str, + ) -> str: + """Returns a fully-qualified agent string.""" + return ( + "projects/{project}/locations/{location}/apps/{app}/agents/{agent}".format( + project=project, + location=location, + app=app, + agent=agent, + ) + ) + + @staticmethod + def parse_agent_path(path: str) -> Dict[str, str]: + """Parses a agent path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/apps/(?P.+?)/agents/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def session_path( + project: str, + location: str, + app: str, + session: str, + ) -> str: + """Returns a fully-qualified session string.""" + return "projects/{project}/locations/{location}/apps/{app}/sessions/{session}".format( + project=project, + location=location, + app=app, + session=session, + ) + + @staticmethod + def parse_session_path(path: str) -> Dict[str, str]: + """Parses a session path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/apps/(?P.+?)/sessions/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def tool_path( + project: str, + location: str, + app: str, + tool: str, + ) -> str: + """Returns a fully-qualified tool string.""" + return "projects/{project}/locations/{location}/apps/{app}/tools/{tool}".format( + project=project, + location=location, + app=app, + tool=tool, + ) + + @staticmethod + def parse_tool_path(path: str) -> Dict[str, str]: + """Parses a tool path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/apps/(?P.+?)/tools/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def toolset_path( + project: str, + location: str, + app: str, + toolset: str, + ) -> str: + """Returns a fully-qualified toolset string.""" + return "projects/{project}/locations/{location}/apps/{app}/toolsets/{toolset}".format( + project=project, + location=location, + app=app, + toolset=toolset, + ) + + @staticmethod + def parse_toolset_path(path: str) -> Dict[str, str]: + """Parses a toolset path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/apps/(?P.+?)/toolsets/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = SessionServiceClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = SessionServiceClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = SessionServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = SessionServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = SessionServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = SessionServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, SessionServiceTransport, Callable[..., SessionServiceTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the session service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,SessionServiceTransport,Callable[..., SessionServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the SessionServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + SessionServiceClient._read_environment_variables() + ) + self._client_cert_source = SessionServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = SessionServiceClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, SessionServiceTransport) + if transport_provided: + # transport is a SessionServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(SessionServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or SessionServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[SessionServiceTransport], Callable[..., SessionServiceTransport] + ] = ( + SessionServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., SessionServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.ces_v1beta.SessionServiceClient`.", + extra={ + "serviceName": "google.cloud.ces.v1beta.SessionService", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.cloud.ces.v1beta.SessionService", + "credentialsType": None, + }, + ) + + def run_session( + self, + request: Optional[Union[session_service.RunSessionRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> session_service.RunSessionResponse: + r"""Initiates a single turn interaction with the CES + agent within a session. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_run_session(): + # Create a client + client = ces_v1beta.SessionServiceClient() + + # Initialize request argument(s) + config = ces_v1beta.SessionConfig() + config.session = "session_value" + + inputs = ces_v1beta.SessionInput() + inputs.text = "text_value" + + request = ces_v1beta.RunSessionRequest( + config=config, + inputs=inputs, + ) + + # Make the request + response = client.run_session(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.RunSessionRequest, dict]): + The request object. Request message for + [SessionService.RunSession][google.cloud.ces.v1beta.SessionService.RunSession]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.RunSessionResponse: + Response message for + [SessionService.RunSession][google.cloud.ces.v1beta.SessionService.RunSession]. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, session_service.RunSessionRequest): + request = session_service.RunSessionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.run_session] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("config.session", request.config.session),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def bidi_run_session( + self, + requests: Optional[Iterator[session_service.BidiSessionClientMessage]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> Iterable[session_service.BidiSessionServerMessage]: + r"""Establishes a bidirectional streaming connection with the CES + agent. The agent processes continuous multimodal inputs (e.g., + text, audio) and generates real-time multimodal output streams. + + --- Client Request Stream --- The client streams requests in the + following order: + + 1. Initialization: The first message must contain + [SessionConfig][google.cloud.ces.v1beta.BidiSessionClientMessage.config]. + For audio sessions, this should also include + [InputAudioConfig][google.cloud.ces.v1beta.SessionConfig.input_audio_config] + and + [OutputAudioConfig][google.cloud.ces.v1beta.SessionConfig.output_audio_config] + to define audio processing and synthesis parameters. + + 2. Interaction: Subsequent messages stream + [SessionInput][google.cloud.ces.v1beta.BidiSessionClientMessage.realtime_input] + containing real-time user input data. + + 3. Termination: The client should half-close the stream when + there is no more user input. It should also half-close upon + receiving + [EndSession][google.cloud.ces.v1beta.BidiSessionServerMessage.end_session] + or + [GoAway][google.cloud.ces.v1beta.BidiSessionServerMessage.go_away] + from the agent. + + --- Server Response Stream --- For each interaction turn, the + agent streams messages in the following sequence: + + 1. Speech Recognition (First N messages): Contains + [RecognitionResult][google.cloud.ces.v1beta.BidiSessionServerMessage.recognition_result] + representing the concatenated user speech segments captured + so far. This is only populated for audio sessions. + + 2. Response (Next M messages): Contains + [SessionOutput][google.cloud.ces.v1beta.BidiSessionServerMessage.session_output] + delivering the agent's response in various modalities (e.g., + text, audio). + + 3. Turn Completion (Final message of the turn): Contains + [SessionOutput][google.cloud.ces.v1beta.BidiSessionServerMessage.session_output] + with + [turn_completed][google.cloud.ces.v1beta.SessionOutput.turn_completed] + set to true. This signals the end of the current turn and + includes + [DiagnosticInfo][google.cloud.ces.v1beta.SessionOutput.diagnostic_info] + with execution details. + + --- Audio Best Practices --- + + 1. Streaming: Stream [audio + data][google.cloud.ces.v1beta.SessionInput.audio] + **CONTINUOUSLY**, even during silence. Recommended chunk + size: 40-120ms (balances latency vs. efficiency). + + 2. Playback & Interruption: Play [audio + responses][google.cloud.ces.v1beta.SessionOutput.audio] upon + receipt. Stop playback immediately if an + [InterruptionSignal][google.cloud.ces.v1beta.BidiSessionServerMessage.interruption_signal] + is received (e.g., user barge-in or new agent response). + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_bidi_run_session(): + # Create a client + client = ces_v1beta.SessionServiceClient() + + # Initialize request argument(s) + config = ces_v1beta.SessionConfig() + config.session = "session_value" + + request = ces_v1beta.BidiSessionClientMessage( + config=config, + ) + + # This method expects an iterator which contains + # 'ces_v1beta.BidiSessionClientMessage' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = client.bidi_run_session(requests=request_generator()) + + # Handle the response + for response in stream: + print(response) + + Args: + requests (Iterator[google.cloud.ces_v1beta.types.BidiSessionClientMessage]): + The request object iterator. The top-level message sent by the client for the + [SessionService.BidiRunSession][google.cloud.ces.v1beta.SessionService.BidiRunSession] + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + Iterable[google.cloud.ces_v1beta.types.BidiSessionServerMessage]: + The top-level message returned from + [SessionService.BidiRunSession][google.cloud.ces.v1beta.SessionService.BidiRunSession] + method. + + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.bidi_run_session] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "SessionServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("SessionServiceClient",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/README.rst b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/README.rst new file mode 100644 index 000000000000..f67320e75a5d --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`SessionServiceTransport` is the ABC for all transports. +- public child `SessionServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `SessionServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseSessionServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `SessionServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/__init__.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/__init__.py new file mode 100644 index 000000000000..d258a984225b --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# 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 collections import OrderedDict +from typing import Dict, Type + +from .base import SessionServiceTransport +from .grpc import SessionServiceGrpcTransport +from .grpc_asyncio import SessionServiceGrpcAsyncIOTransport +from .rest import SessionServiceRestInterceptor, SessionServiceRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SessionServiceTransport]] +_transport_registry["grpc"] = SessionServiceGrpcTransport +_transport_registry["grpc_asyncio"] = SessionServiceGrpcAsyncIOTransport +_transport_registry["rest"] = SessionServiceRestTransport + +__all__ = ( + "SessionServiceTransport", + "SessionServiceGrpcTransport", + "SessionServiceGrpcAsyncIOTransport", + "SessionServiceRestTransport", + "SessionServiceRestInterceptor", +) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/base.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/base.py new file mode 100644 index 000000000000..e205d75a035c --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/base.py @@ -0,0 +1,298 @@ +# -*- coding: utf-8 -*- +# 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. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +import google.auth # type: ignore +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.ces_v1beta import gapic_version as package_version +from google.cloud.ces_v1beta.types import session_service + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class SessionServiceTransport(abc.ABC): + """Abstract transport class for SessionService.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/ces", + "https://www.googleapis.com/auth/cloud-platform", + ) + + DEFAULT_HOST: str = "ces.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'ces.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.run_session: gapic_v1.method.wrap_method( + self.run_session, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + deadline=220.0, + ), + default_timeout=220.0, + client_info=client_info, + ), + self.bidi_run_session: gapic_v1.method.wrap_method( + self.bidi_run_session, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + deadline=3600.0, + ), + default_timeout=3600.0, + client_info=client_info, + ), + self.get_location: gapic_v1.method.wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: gapic_v1.method.wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def run_session( + self, + ) -> Callable[ + [session_service.RunSessionRequest], + Union[ + session_service.RunSessionResponse, + Awaitable[session_service.RunSessionResponse], + ], + ]: + raise NotImplementedError() + + @property + def bidi_run_session( + self, + ) -> Callable[ + [session_service.BidiSessionClientMessage], + Union[ + session_service.BidiSessionServerMessage, + Awaitable[session_service.BidiSessionServerMessage], + ], + ]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def get_location( + self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[ + locations_pb2.ListLocationsResponse, + Awaitable[locations_pb2.ListLocationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("SessionServiceTransport",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/grpc.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/grpc.py new file mode 100644 index 000000000000..e4daba54f0fc --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/grpc.py @@ -0,0 +1,559 @@ +# -*- coding: utf-8 -*- +# 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. +# +import json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson + +from google.cloud.ces_v1beta.types import session_service + +from .base import DEFAULT_CLIENT_INFO, SessionServiceTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.ces.v1beta.SessionService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.ces.v1beta.SessionService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class SessionServiceGrpcTransport(SessionServiceTransport): + """gRPC backend transport for SessionService. + + Session service provides APIs for interacting with CES + agents. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "ces.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'ces.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "ces.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def run_session( + self, + ) -> Callable[ + [session_service.RunSessionRequest], session_service.RunSessionResponse + ]: + r"""Return a callable for the run session method over gRPC. + + Initiates a single turn interaction with the CES + agent within a session. + + Returns: + Callable[[~.RunSessionRequest], + ~.RunSessionResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "run_session" not in self._stubs: + self._stubs["run_session"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.SessionService/RunSession", + request_serializer=session_service.RunSessionRequest.serialize, + response_deserializer=session_service.RunSessionResponse.deserialize, + ) + return self._stubs["run_session"] + + @property + def bidi_run_session( + self, + ) -> Callable[ + [session_service.BidiSessionClientMessage], + session_service.BidiSessionServerMessage, + ]: + r"""Return a callable for the bidi run session method over gRPC. + + Establishes a bidirectional streaming connection with the CES + agent. The agent processes continuous multimodal inputs (e.g., + text, audio) and generates real-time multimodal output streams. + + --- Client Request Stream --- The client streams requests in the + following order: + + 1. Initialization: The first message must contain + [SessionConfig][google.cloud.ces.v1beta.BidiSessionClientMessage.config]. + For audio sessions, this should also include + [InputAudioConfig][google.cloud.ces.v1beta.SessionConfig.input_audio_config] + and + [OutputAudioConfig][google.cloud.ces.v1beta.SessionConfig.output_audio_config] + to define audio processing and synthesis parameters. + + 2. Interaction: Subsequent messages stream + [SessionInput][google.cloud.ces.v1beta.BidiSessionClientMessage.realtime_input] + containing real-time user input data. + + 3. Termination: The client should half-close the stream when + there is no more user input. It should also half-close upon + receiving + [EndSession][google.cloud.ces.v1beta.BidiSessionServerMessage.end_session] + or + [GoAway][google.cloud.ces.v1beta.BidiSessionServerMessage.go_away] + from the agent. + + --- Server Response Stream --- For each interaction turn, the + agent streams messages in the following sequence: + + 1. Speech Recognition (First N messages): Contains + [RecognitionResult][google.cloud.ces.v1beta.BidiSessionServerMessage.recognition_result] + representing the concatenated user speech segments captured + so far. This is only populated for audio sessions. + + 2. Response (Next M messages): Contains + [SessionOutput][google.cloud.ces.v1beta.BidiSessionServerMessage.session_output] + delivering the agent's response in various modalities (e.g., + text, audio). + + 3. Turn Completion (Final message of the turn): Contains + [SessionOutput][google.cloud.ces.v1beta.BidiSessionServerMessage.session_output] + with + [turn_completed][google.cloud.ces.v1beta.SessionOutput.turn_completed] + set to true. This signals the end of the current turn and + includes + [DiagnosticInfo][google.cloud.ces.v1beta.SessionOutput.diagnostic_info] + with execution details. + + --- Audio Best Practices --- + + 1. Streaming: Stream [audio + data][google.cloud.ces.v1beta.SessionInput.audio] + **CONTINUOUSLY**, even during silence. Recommended chunk + size: 40-120ms (balances latency vs. efficiency). + + 2. Playback & Interruption: Play [audio + responses][google.cloud.ces.v1beta.SessionOutput.audio] upon + receipt. Stop playback immediately if an + [InterruptionSignal][google.cloud.ces.v1beta.BidiSessionServerMessage.interruption_signal] + is received (e.g., user barge-in or new agent response). + + Returns: + Callable[[~.BidiSessionClientMessage], + ~.BidiSessionServerMessage]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "bidi_run_session" not in self._stubs: + self._stubs["bidi_run_session"] = self._logged_channel.stream_stream( + "/google.cloud.ces.v1beta.SessionService/BidiRunSession", + request_serializer=session_service.BidiSessionClientMessage.serialize, + response_deserializer=session_service.BidiSessionServerMessage.deserialize, + ) + return self._stubs["bidi_run_session"] + + def close(self): + self._logged_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("SessionServiceGrpcTransport",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/grpc_asyncio.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..87aada3f8ac3 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/grpc_asyncio.py @@ -0,0 +1,632 @@ +# -*- coding: utf-8 -*- +# 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. +# +import inspect +import json +import logging as std_logging +import pickle +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +from grpc.experimental import aio # type: ignore + +from google.cloud.ces_v1beta.types import session_service + +from .base import DEFAULT_CLIENT_INFO, SessionServiceTransport +from .grpc import SessionServiceGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.ces.v1beta.SessionService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.ces.v1beta.SessionService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class SessionServiceGrpcAsyncIOTransport(SessionServiceTransport): + """gRPC AsyncIO backend transport for SessionService. + + Session service provides APIs for interacting with CES + agents. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "ces.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "ces.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'ces.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def run_session( + self, + ) -> Callable[ + [session_service.RunSessionRequest], + Awaitable[session_service.RunSessionResponse], + ]: + r"""Return a callable for the run session method over gRPC. + + Initiates a single turn interaction with the CES + agent within a session. + + Returns: + Callable[[~.RunSessionRequest], + Awaitable[~.RunSessionResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "run_session" not in self._stubs: + self._stubs["run_session"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.SessionService/RunSession", + request_serializer=session_service.RunSessionRequest.serialize, + response_deserializer=session_service.RunSessionResponse.deserialize, + ) + return self._stubs["run_session"] + + @property + def bidi_run_session( + self, + ) -> Callable[ + [session_service.BidiSessionClientMessage], + Awaitable[session_service.BidiSessionServerMessage], + ]: + r"""Return a callable for the bidi run session method over gRPC. + + Establishes a bidirectional streaming connection with the CES + agent. The agent processes continuous multimodal inputs (e.g., + text, audio) and generates real-time multimodal output streams. + + --- Client Request Stream --- The client streams requests in the + following order: + + 1. Initialization: The first message must contain + [SessionConfig][google.cloud.ces.v1beta.BidiSessionClientMessage.config]. + For audio sessions, this should also include + [InputAudioConfig][google.cloud.ces.v1beta.SessionConfig.input_audio_config] + and + [OutputAudioConfig][google.cloud.ces.v1beta.SessionConfig.output_audio_config] + to define audio processing and synthesis parameters. + + 2. Interaction: Subsequent messages stream + [SessionInput][google.cloud.ces.v1beta.BidiSessionClientMessage.realtime_input] + containing real-time user input data. + + 3. Termination: The client should half-close the stream when + there is no more user input. It should also half-close upon + receiving + [EndSession][google.cloud.ces.v1beta.BidiSessionServerMessage.end_session] + or + [GoAway][google.cloud.ces.v1beta.BidiSessionServerMessage.go_away] + from the agent. + + --- Server Response Stream --- For each interaction turn, the + agent streams messages in the following sequence: + + 1. Speech Recognition (First N messages): Contains + [RecognitionResult][google.cloud.ces.v1beta.BidiSessionServerMessage.recognition_result] + representing the concatenated user speech segments captured + so far. This is only populated for audio sessions. + + 2. Response (Next M messages): Contains + [SessionOutput][google.cloud.ces.v1beta.BidiSessionServerMessage.session_output] + delivering the agent's response in various modalities (e.g., + text, audio). + + 3. Turn Completion (Final message of the turn): Contains + [SessionOutput][google.cloud.ces.v1beta.BidiSessionServerMessage.session_output] + with + [turn_completed][google.cloud.ces.v1beta.SessionOutput.turn_completed] + set to true. This signals the end of the current turn and + includes + [DiagnosticInfo][google.cloud.ces.v1beta.SessionOutput.diagnostic_info] + with execution details. + + --- Audio Best Practices --- + + 1. Streaming: Stream [audio + data][google.cloud.ces.v1beta.SessionInput.audio] + **CONTINUOUSLY**, even during silence. Recommended chunk + size: 40-120ms (balances latency vs. efficiency). + + 2. Playback & Interruption: Play [audio + responses][google.cloud.ces.v1beta.SessionOutput.audio] upon + receipt. Stop playback immediately if an + [InterruptionSignal][google.cloud.ces.v1beta.BidiSessionServerMessage.interruption_signal] + is received (e.g., user barge-in or new agent response). + + Returns: + Callable[[~.BidiSessionClientMessage], + Awaitable[~.BidiSessionServerMessage]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "bidi_run_session" not in self._stubs: + self._stubs["bidi_run_session"] = self._logged_channel.stream_stream( + "/google.cloud.ces.v1beta.SessionService/BidiRunSession", + request_serializer=session_service.BidiSessionClientMessage.serialize, + response_deserializer=session_service.BidiSessionServerMessage.deserialize, + ) + return self._stubs["bidi_run_session"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.run_session: self._wrap_method( + self.run_session, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + deadline=220.0, + ), + default_timeout=220.0, + client_info=client_info, + ), + self.bidi_run_session: self._wrap_method( + self.bidi_run_session, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + deadline=3600.0, + ), + default_timeout=3600.0, + client_info=client_info, + ), + self.get_location: self._wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: self._wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + +__all__ = ("SessionServiceGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/rest.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/rest.py new file mode 100644 index 000000000000..7b1a8caf4a70 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/rest.py @@ -0,0 +1,1372 @@ +# -*- coding: utf-8 -*- +# 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. +# +import dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.ces_v1beta.types import session_service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseSessionServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class SessionServiceRestInterceptor: + """Interceptor for SessionService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the SessionServiceRestTransport. + + .. code-block:: python + class MyCustomSessionServiceInterceptor(SessionServiceRestInterceptor): + def pre_run_session(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_run_session(self, response): + logging.log(f"Received response: {response}") + return response + + transport = SessionServiceRestTransport(interceptor=MyCustomSessionServiceInterceptor()) + client = SessionServiceClient(transport=transport) + + + """ + + def pre_run_session( + self, + request: session_service.RunSessionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + session_service.RunSessionRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for run_session + + Override in a subclass to manipulate the request or metadata + before they are sent to the SessionService server. + """ + return request, metadata + + def post_run_session( + self, response: session_service.RunSessionResponse + ) -> session_service.RunSessionResponse: + """Post-rpc interceptor for run_session + + DEPRECATED. Please use the `post_run_session_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SessionService server but before + it is returned to user code. This `post_run_session` interceptor runs + before the `post_run_session_with_metadata` interceptor. + """ + return response + + def post_run_session_with_metadata( + self, + response: session_service.RunSessionResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + session_service.RunSessionResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for run_session + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SessionService server but before it is returned to user code. + + We recommend only using this `post_run_session_with_metadata` + interceptor in new development instead of the `post_run_session` interceptor. + When both interceptors are used, this `post_run_session_with_metadata` interceptor runs after the + `post_run_session` interceptor. The (possibly modified) response returned by + `post_run_session` will be passed to + `post_run_session_with_metadata`. + """ + return response, metadata + + def pre_get_location( + self, + request: locations_pb2.GetLocationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the SessionService server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.Location + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the SessionService server but before + it is returned to user code. + """ + return response + + def pre_list_locations( + self, + request: locations_pb2.ListLocationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the SessionService server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsResponse + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the SessionService server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the SessionService server. + """ + return request, metadata + + def post_cancel_operation(self, response: None) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the SessionService server but before + it is returned to user code. + """ + return response + + def pre_delete_operation( + self, + request: operations_pb2.DeleteOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the SessionService server. + """ + return request, metadata + + def post_delete_operation(self, response: None) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the SessionService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the SessionService server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the SessionService server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the SessionService server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the SessionService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class SessionServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: SessionServiceRestInterceptor + + +class SessionServiceRestTransport(_BaseSessionServiceRestTransport): + """REST backend synchronous transport for SessionService. + + Session service provides APIs for interacting with CES + agents. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "ces.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[SessionServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'ces.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or SessionServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _BidiRunSession( + _BaseSessionServiceRestTransport._BaseBidiRunSession, SessionServiceRestStub + ): + def __hash__(self): + return hash("SessionServiceRestTransport.BidiRunSession") + + def __call__( + self, + request: session_service.BidiSessionClientMessage, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> rest_streaming.ResponseIterator: + raise NotImplementedError( + "Method BidiRunSession is not available over REST transport" + ) + + class _RunSession( + _BaseSessionServiceRestTransport._BaseRunSession, SessionServiceRestStub + ): + def __hash__(self): + return hash("SessionServiceRestTransport.RunSession") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: session_service.RunSessionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> session_service.RunSessionResponse: + r"""Call the run session method over HTTP. + + Args: + request (~.session_service.RunSessionRequest): + The request object. Request message for + [SessionService.RunSession][google.cloud.ces.v1beta.SessionService.RunSession]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.session_service.RunSessionResponse: + Response message for + [SessionService.RunSession][google.cloud.ces.v1beta.SessionService.RunSession]. + + """ + + http_options = ( + _BaseSessionServiceRestTransport._BaseRunSession._get_http_options() + ) + + request, metadata = self._interceptor.pre_run_session(request, metadata) + transcoded_request = _BaseSessionServiceRestTransport._BaseRunSession._get_transcoded_request( + http_options, request + ) + + body = ( + _BaseSessionServiceRestTransport._BaseRunSession._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSessionServiceRestTransport._BaseRunSession._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.SessionServiceClient.RunSession", + extra={ + "serviceName": "google.cloud.ces.v1beta.SessionService", + "rpcName": "RunSession", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SessionServiceRestTransport._RunSession._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = session_service.RunSessionResponse() + pb_resp = session_service.RunSessionResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_run_session(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_run_session_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = session_service.RunSessionResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.SessionServiceClient.run_session", + extra={ + "serviceName": "google.cloud.ces.v1beta.SessionService", + "rpcName": "RunSession", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def bidi_run_session( + self, + ) -> Callable[ + [session_service.BidiSessionClientMessage], + session_service.BidiSessionServerMessage, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BidiRunSession(self._session, self._host, self._interceptor) # type: ignore + + @property + def run_session( + self, + ) -> Callable[ + [session_service.RunSessionRequest], session_service.RunSessionResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RunSession(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation( + _BaseSessionServiceRestTransport._BaseGetLocation, SessionServiceRestStub + ): + def __hash__(self): + return hash("SessionServiceRestTransport.GetLocation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: locations_pb2.GetLocationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options = ( + _BaseSessionServiceRestTransport._BaseGetLocation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_location(request, metadata) + transcoded_request = _BaseSessionServiceRestTransport._BaseGetLocation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSessionServiceRestTransport._BaseGetLocation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.SessionServiceClient.GetLocation", + extra={ + "serviceName": "google.cloud.ces.v1beta.SessionService", + "rpcName": "GetLocation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SessionServiceRestTransport._GetLocation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.Location() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_location(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.SessionServiceAsyncClient.GetLocation", + extra={ + "serviceName": "google.cloud.ces.v1beta.SessionService", + "rpcName": "GetLocation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations( + _BaseSessionServiceRestTransport._BaseListLocations, SessionServiceRestStub + ): + def __hash__(self): + return hash("SessionServiceRestTransport.ListLocations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: locations_pb2.ListLocationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options = ( + _BaseSessionServiceRestTransport._BaseListLocations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + transcoded_request = _BaseSessionServiceRestTransport._BaseListLocations._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSessionServiceRestTransport._BaseListLocations._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.SessionServiceClient.ListLocations", + extra={ + "serviceName": "google.cloud.ces.v1beta.SessionService", + "rpcName": "ListLocations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SessionServiceRestTransport._ListLocations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_locations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.SessionServiceAsyncClient.ListLocations", + extra={ + "serviceName": "google.cloud.ces.v1beta.SessionService", + "rpcName": "ListLocations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation( + _BaseSessionServiceRestTransport._BaseCancelOperation, SessionServiceRestStub + ): + def __hash__(self): + return hash("SessionServiceRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseSessionServiceRestTransport._BaseCancelOperation._get_http_options() + + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + transcoded_request = _BaseSessionServiceRestTransport._BaseCancelOperation._get_transcoded_request( + http_options, request + ) + + body = _BaseSessionServiceRestTransport._BaseCancelOperation._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSessionServiceRestTransport._BaseCancelOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.SessionServiceClient.CancelOperation", + extra={ + "serviceName": "google.cloud.ces.v1beta.SessionService", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SessionServiceRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation( + _BaseSessionServiceRestTransport._BaseDeleteOperation, SessionServiceRestStub + ): + def __hash__(self): + return hash("SessionServiceRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.DeleteOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = _BaseSessionServiceRestTransport._BaseDeleteOperation._get_http_options() + + request, metadata = self._interceptor.pre_delete_operation( + request, metadata + ) + transcoded_request = _BaseSessionServiceRestTransport._BaseDeleteOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSessionServiceRestTransport._BaseDeleteOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.SessionServiceClient.DeleteOperation", + extra={ + "serviceName": "google.cloud.ces.v1beta.SessionService", + "rpcName": "DeleteOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SessionServiceRestTransport._DeleteOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation( + _BaseSessionServiceRestTransport._BaseGetOperation, SessionServiceRestStub + ): + def __hash__(self): + return hash("SessionServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = ( + _BaseSessionServiceRestTransport._BaseGetOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseSessionServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSessionServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.SessionServiceClient.GetOperation", + extra={ + "serviceName": "google.cloud.ces.v1beta.SessionService", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SessionServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.SessionServiceAsyncClient.GetOperation", + extra={ + "serviceName": "google.cloud.ces.v1beta.SessionService", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations( + _BaseSessionServiceRestTransport._BaseListOperations, SessionServiceRestStub + ): + def __hash__(self): + return hash("SessionServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options = ( + _BaseSessionServiceRestTransport._BaseListOperations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = _BaseSessionServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSessionServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.SessionServiceClient.ListOperations", + extra={ + "serviceName": "google.cloud.ces.v1beta.SessionService", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SessionServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.SessionServiceAsyncClient.ListOperations", + extra={ + "serviceName": "google.cloud.ces.v1beta.SessionService", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("SessionServiceRestTransport",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/rest_base.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/rest_base.py new file mode 100644 index 000000000000..6f0b7c555927 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/session_service/transports/rest_base.py @@ -0,0 +1,310 @@ +# -*- coding: utf-8 -*- +# 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. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.ces_v1beta.types import session_service + +from .base import DEFAULT_CLIENT_INFO, SessionServiceTransport + + +class _BaseSessionServiceRestTransport(SessionServiceTransport): + """Base REST backend transport for SessionService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "ces.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'ces.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseBidiRunSession: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + class _BaseRunSession: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{config.session=projects/*/locations/*/apps/*/sessions/*}:runSession", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = session_service.RunSessionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSessionServiceRestTransport._BaseRunSession._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetLocation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListLocations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*}/locations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseSessionServiceRestTransport",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/tool_service/__init__.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/tool_service/__init__.py new file mode 100644 index 000000000000..ea636aad3f0d --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/tool_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# 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 .async_client import ToolServiceAsyncClient +from .client import ToolServiceClient + +__all__ = ( + "ToolServiceClient", + "ToolServiceAsyncClient", +) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/tool_service/async_client.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/tool_service/async_client.py new file mode 100644 index 000000000000..adaffbd486c7 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/tool_service/async_client.py @@ -0,0 +1,913 @@ +# -*- coding: utf-8 -*- +# 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. +# +import logging as std_logging +import re +from collections import OrderedDict +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.ces_v1beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +import google.protobuf.struct_pb2 as struct_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.ces_v1beta.types import schema, tool, tool_service, toolset_tool + +from .client import ToolServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, ToolServiceTransport +from .transports.grpc_asyncio import ToolServiceGrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class ToolServiceAsyncClient: + """Tool service provides APIs for interacting with CES tools.""" + + _client: ToolServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = ToolServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ToolServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = ToolServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = ToolServiceClient._DEFAULT_UNIVERSE + + app_path = staticmethod(ToolServiceClient.app_path) + parse_app_path = staticmethod(ToolServiceClient.parse_app_path) + secret_version_path = staticmethod(ToolServiceClient.secret_version_path) + parse_secret_version_path = staticmethod( + ToolServiceClient.parse_secret_version_path + ) + service_path = staticmethod(ToolServiceClient.service_path) + parse_service_path = staticmethod(ToolServiceClient.parse_service_path) + tool_path = staticmethod(ToolServiceClient.tool_path) + parse_tool_path = staticmethod(ToolServiceClient.parse_tool_path) + toolset_path = staticmethod(ToolServiceClient.toolset_path) + parse_toolset_path = staticmethod(ToolServiceClient.parse_toolset_path) + common_billing_account_path = staticmethod( + ToolServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + ToolServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(ToolServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(ToolServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(ToolServiceClient.common_organization_path) + parse_common_organization_path = staticmethod( + ToolServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod(ToolServiceClient.common_project_path) + parse_common_project_path = staticmethod( + ToolServiceClient.parse_common_project_path + ) + common_location_path = staticmethod(ToolServiceClient.common_location_path) + parse_common_location_path = staticmethod( + ToolServiceClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ToolServiceAsyncClient: The constructed client. + """ + sa_info_func = ( + ToolServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(ToolServiceAsyncClient, info, *args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ToolServiceAsyncClient: The constructed client. + """ + sa_file_func = ( + ToolServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(ToolServiceAsyncClient, filename, *args, **kwargs) + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return ToolServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ToolServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ToolServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = ToolServiceClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, ToolServiceTransport, Callable[..., ToolServiceTransport]] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the tool service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,ToolServiceTransport,Callable[..., ToolServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the ToolServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = ToolServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.ces_v1beta.ToolServiceAsyncClient`.", + extra={ + "serviceName": "google.cloud.ces.v1beta.ToolService", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.cloud.ces.v1beta.ToolService", + "credentialsType": None, + }, + ) + + async def execute_tool( + self, + request: Optional[Union[tool_service.ExecuteToolRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> tool_service.ExecuteToolResponse: + r"""Executes the given tool with the given arguments. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_execute_tool(): + # Create a client + client = ces_v1beta.ToolServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ExecuteToolRequest( + tool="tool_value", + parent="parent_value", + ) + + # Make the request + response = await client.execute_tool(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.ExecuteToolRequest, dict]]): + The request object. Request message for + [ToolService.ExecuteTool][google.cloud.ces.v1beta.ToolService.ExecuteTool]. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.ExecuteToolResponse: + Response message for + [ToolService.ExecuteTool][google.cloud.ces.v1beta.ToolService.ExecuteTool]. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, tool_service.ExecuteToolRequest): + request = tool_service.ExecuteToolRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.execute_tool + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def retrieve_tool_schema( + self, + request: Optional[Union[tool_service.RetrieveToolSchemaRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> tool_service.RetrieveToolSchemaResponse: + r"""Retrieve the schema of the given tool. The schema is + computed on the fly for the given instance of the tool. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_retrieve_tool_schema(): + # Create a client + client = ces_v1beta.ToolServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.RetrieveToolSchemaRequest( + tool="tool_value", + parent="parent_value", + ) + + # Make the request + response = await client.retrieve_tool_schema(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.RetrieveToolSchemaRequest, dict]]): + The request object. Request message for + [ToolService.RetrieveToolSchema][google.cloud.ces.v1beta.ToolService.RetrieveToolSchema]. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.RetrieveToolSchemaResponse: + Response message for + [ToolService.RetrieveToolSchema][google.cloud.ces.v1beta.ToolService.RetrieveToolSchema]. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, tool_service.RetrieveToolSchemaRequest): + request = tool_service.RetrieveToolSchemaRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.retrieve_tool_schema + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def retrieve_tools( + self, + request: Optional[Union[tool_service.RetrieveToolsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> tool_service.RetrieveToolsResponse: + r"""Retrieve the list of tools included in the specified + toolset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_retrieve_tools(): + # Create a client + client = ces_v1beta.ToolServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.RetrieveToolsRequest( + toolset="toolset_value", + ) + + # Make the request + response = await client.retrieve_tools(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.RetrieveToolsRequest, dict]]): + The request object. Request message for + [ToolService.RetrieveTools][google.cloud.ces.v1beta.ToolService.RetrieveTools]. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.RetrieveToolsResponse: + Response message for + [ToolService.RetrieveTools][google.cloud.ces.v1beta.ToolService.RetrieveTools]. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, tool_service.RetrieveToolsRequest): + request = tool_service.RetrieveToolsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.retrieve_tools + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("toolset", request.toolset),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.delete_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "ToolServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("ToolServiceAsyncClient",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/tool_service/client.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/tool_service/client.py new file mode 100644 index 000000000000..da2e8a87a67c --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/tool_service/client.py @@ -0,0 +1,1444 @@ +# -*- coding: utf-8 -*- +# 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. +# +import json +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.ces_v1beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +import google.protobuf.struct_pb2 as struct_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.ces_v1beta.types import schema, tool, tool_service, toolset_tool + +from .transports.base import DEFAULT_CLIENT_INFO, ToolServiceTransport +from .transports.grpc import ToolServiceGrpcTransport +from .transports.grpc_asyncio import ToolServiceGrpcAsyncIOTransport +from .transports.rest import ToolServiceRestTransport + + +class ToolServiceClientMeta(type): + """Metaclass for the ToolService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[ToolServiceTransport]] + _transport_registry["grpc"] = ToolServiceGrpcTransport + _transport_registry["grpc_asyncio"] = ToolServiceGrpcAsyncIOTransport + _transport_registry["rest"] = ToolServiceRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[ToolServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class ToolServiceClient(metaclass=ToolServiceClientMeta): + """Tool service provides APIs for interacting with CES tools.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "ces.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "ces.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ToolServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ToolServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> ToolServiceTransport: + """Returns the transport used by the client instance. + + Returns: + ToolServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def app_path( + project: str, + location: str, + app: str, + ) -> str: + """Returns a fully-qualified app string.""" + return "projects/{project}/locations/{location}/apps/{app}".format( + project=project, + location=location, + app=app, + ) + + @staticmethod + def parse_app_path(path: str) -> Dict[str, str]: + """Parses a app path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/apps/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def secret_version_path( + project: str, + secret: str, + secret_version: str, + ) -> str: + """Returns a fully-qualified secret_version string.""" + return "projects/{project}/secrets/{secret}/versions/{secret_version}".format( + project=project, + secret=secret, + secret_version=secret_version, + ) + + @staticmethod + def parse_secret_version_path(path: str) -> Dict[str, str]: + """Parses a secret_version path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/secrets/(?P.+?)/versions/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def service_path( + project: str, + location: str, + namespace: str, + service: str, + ) -> str: + """Returns a fully-qualified service string.""" + return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format( + project=project, + location=location, + namespace=namespace, + service=service, + ) + + @staticmethod + def parse_service_path(path: str) -> Dict[str, str]: + """Parses a service path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)/services/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def tool_path( + project: str, + location: str, + app: str, + tool: str, + ) -> str: + """Returns a fully-qualified tool string.""" + return "projects/{project}/locations/{location}/apps/{app}/tools/{tool}".format( + project=project, + location=location, + app=app, + tool=tool, + ) + + @staticmethod + def parse_tool_path(path: str) -> Dict[str, str]: + """Parses a tool path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/apps/(?P.+?)/tools/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def toolset_path( + project: str, + location: str, + app: str, + toolset: str, + ) -> str: + """Returns a fully-qualified toolset string.""" + return "projects/{project}/locations/{location}/apps/{app}/toolsets/{toolset}".format( + project=project, + location=location, + app=app, + toolset=toolset, + ) + + @staticmethod + def parse_toolset_path(path: str) -> Dict[str, str]: + """Parses a toolset path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/apps/(?P.+?)/toolsets/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = ToolServiceClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = ToolServiceClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = ToolServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = ToolServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ToolServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = ToolServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, ToolServiceTransport, Callable[..., ToolServiceTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the tool service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,ToolServiceTransport,Callable[..., ToolServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the ToolServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + ToolServiceClient._read_environment_variables() + ) + self._client_cert_source = ToolServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = ToolServiceClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, ToolServiceTransport) + if transport_provided: + # transport is a ToolServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(ToolServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = self._api_endpoint or ToolServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[ToolServiceTransport], Callable[..., ToolServiceTransport] + ] = ( + ToolServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., ToolServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.ces_v1beta.ToolServiceClient`.", + extra={ + "serviceName": "google.cloud.ces.v1beta.ToolService", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.cloud.ces.v1beta.ToolService", + "credentialsType": None, + }, + ) + + def execute_tool( + self, + request: Optional[Union[tool_service.ExecuteToolRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> tool_service.ExecuteToolResponse: + r"""Executes the given tool with the given arguments. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_execute_tool(): + # Create a client + client = ces_v1beta.ToolServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ExecuteToolRequest( + tool="tool_value", + parent="parent_value", + ) + + # Make the request + response = client.execute_tool(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.ExecuteToolRequest, dict]): + The request object. Request message for + [ToolService.ExecuteTool][google.cloud.ces.v1beta.ToolService.ExecuteTool]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.ExecuteToolResponse: + Response message for + [ToolService.ExecuteTool][google.cloud.ces.v1beta.ToolService.ExecuteTool]. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, tool_service.ExecuteToolRequest): + request = tool_service.ExecuteToolRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.execute_tool] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def retrieve_tool_schema( + self, + request: Optional[Union[tool_service.RetrieveToolSchemaRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> tool_service.RetrieveToolSchemaResponse: + r"""Retrieve the schema of the given tool. The schema is + computed on the fly for the given instance of the tool. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_retrieve_tool_schema(): + # Create a client + client = ces_v1beta.ToolServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.RetrieveToolSchemaRequest( + tool="tool_value", + parent="parent_value", + ) + + # Make the request + response = client.retrieve_tool_schema(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.RetrieveToolSchemaRequest, dict]): + The request object. Request message for + [ToolService.RetrieveToolSchema][google.cloud.ces.v1beta.ToolService.RetrieveToolSchema]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.RetrieveToolSchemaResponse: + Response message for + [ToolService.RetrieveToolSchema][google.cloud.ces.v1beta.ToolService.RetrieveToolSchema]. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, tool_service.RetrieveToolSchemaRequest): + request = tool_service.RetrieveToolSchemaRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.retrieve_tool_schema] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def retrieve_tools( + self, + request: Optional[Union[tool_service.RetrieveToolsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> tool_service.RetrieveToolsResponse: + r"""Retrieve the list of tools included in the specified + toolset. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_retrieve_tools(): + # Create a client + client = ces_v1beta.ToolServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.RetrieveToolsRequest( + toolset="toolset_value", + ) + + # Make the request + response = client.retrieve_tools(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.RetrieveToolsRequest, dict]): + The request object. Request message for + [ToolService.RetrieveTools][google.cloud.ces.v1beta.ToolService.RetrieveTools]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.RetrieveToolsResponse: + Response message for + [ToolService.RetrieveTools][google.cloud.ces.v1beta.ToolService.RetrieveTools]. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, tool_service.RetrieveToolsRequest): + request = tool_service.RetrieveToolsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.retrieve_tools] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("toolset", request.toolset),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "ToolServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("ToolServiceClient",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/tool_service/transports/README.rst b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/tool_service/transports/README.rst new file mode 100644 index 000000000000..b8d87f66bcf8 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/tool_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`ToolServiceTransport` is the ABC for all transports. +- public child `ToolServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `ToolServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseToolServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `ToolServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/tool_service/transports/__init__.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/tool_service/transports/__init__.py new file mode 100644 index 000000000000..4bb0f04fe0d1 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/tool_service/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# 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 collections import OrderedDict +from typing import Dict, Type + +from .base import ToolServiceTransport +from .grpc import ToolServiceGrpcTransport +from .grpc_asyncio import ToolServiceGrpcAsyncIOTransport +from .rest import ToolServiceRestInterceptor, ToolServiceRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ToolServiceTransport]] +_transport_registry["grpc"] = ToolServiceGrpcTransport +_transport_registry["grpc_asyncio"] = ToolServiceGrpcAsyncIOTransport +_transport_registry["rest"] = ToolServiceRestTransport + +__all__ = ( + "ToolServiceTransport", + "ToolServiceGrpcTransport", + "ToolServiceGrpcAsyncIOTransport", + "ToolServiceRestTransport", + "ToolServiceRestInterceptor", +) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/tool_service/transports/base.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/tool_service/transports/base.py new file mode 100644 index 000000000000..58a6a87c9aae --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/tool_service/transports/base.py @@ -0,0 +1,301 @@ +# -*- coding: utf-8 -*- +# 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. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +import google.auth # type: ignore +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.ces_v1beta import gapic_version as package_version +from google.cloud.ces_v1beta.types import tool_service + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class ToolServiceTransport(abc.ABC): + """Abstract transport class for ToolService.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/ces", + "https://www.googleapis.com/auth/cloud-platform", + ) + + DEFAULT_HOST: str = "ces.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'ces.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.execute_tool: gapic_v1.method.wrap_method( + self.execute_tool, + default_timeout=None, + client_info=client_info, + ), + self.retrieve_tool_schema: gapic_v1.method.wrap_method( + self.retrieve_tool_schema, + default_timeout=None, + client_info=client_info, + ), + self.retrieve_tools: gapic_v1.method.wrap_method( + self.retrieve_tools, + default_timeout=None, + client_info=client_info, + ), + self.get_location: gapic_v1.method.wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: gapic_v1.method.wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def execute_tool( + self, + ) -> Callable[ + [tool_service.ExecuteToolRequest], + Union[ + tool_service.ExecuteToolResponse, + Awaitable[tool_service.ExecuteToolResponse], + ], + ]: + raise NotImplementedError() + + @property + def retrieve_tool_schema( + self, + ) -> Callable[ + [tool_service.RetrieveToolSchemaRequest], + Union[ + tool_service.RetrieveToolSchemaResponse, + Awaitable[tool_service.RetrieveToolSchemaResponse], + ], + ]: + raise NotImplementedError() + + @property + def retrieve_tools( + self, + ) -> Callable[ + [tool_service.RetrieveToolsRequest], + Union[ + tool_service.RetrieveToolsResponse, + Awaitable[tool_service.RetrieveToolsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def get_location( + self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[ + locations_pb2.ListLocationsResponse, + Awaitable[locations_pb2.ListLocationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("ToolServiceTransport",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/tool_service/transports/grpc.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/tool_service/transports/grpc.py new file mode 100644 index 000000000000..b84a8ce14e1b --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/tool_service/transports/grpc.py @@ -0,0 +1,525 @@ +# -*- coding: utf-8 -*- +# 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. +# +import json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson + +from google.cloud.ces_v1beta.types import tool_service + +from .base import DEFAULT_CLIENT_INFO, ToolServiceTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.ces.v1beta.ToolService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.ces.v1beta.ToolService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class ToolServiceGrpcTransport(ToolServiceTransport): + """gRPC backend transport for ToolService. + + Tool service provides APIs for interacting with CES tools. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "ces.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'ces.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "ces.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def execute_tool( + self, + ) -> Callable[[tool_service.ExecuteToolRequest], tool_service.ExecuteToolResponse]: + r"""Return a callable for the execute tool method over gRPC. + + Executes the given tool with the given arguments. + + Returns: + Callable[[~.ExecuteToolRequest], + ~.ExecuteToolResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "execute_tool" not in self._stubs: + self._stubs["execute_tool"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.ToolService/ExecuteTool", + request_serializer=tool_service.ExecuteToolRequest.serialize, + response_deserializer=tool_service.ExecuteToolResponse.deserialize, + ) + return self._stubs["execute_tool"] + + @property + def retrieve_tool_schema( + self, + ) -> Callable[ + [tool_service.RetrieveToolSchemaRequest], + tool_service.RetrieveToolSchemaResponse, + ]: + r"""Return a callable for the retrieve tool schema method over gRPC. + + Retrieve the schema of the given tool. The schema is + computed on the fly for the given instance of the tool. + + Returns: + Callable[[~.RetrieveToolSchemaRequest], + ~.RetrieveToolSchemaResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "retrieve_tool_schema" not in self._stubs: + self._stubs["retrieve_tool_schema"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.ToolService/RetrieveToolSchema", + request_serializer=tool_service.RetrieveToolSchemaRequest.serialize, + response_deserializer=tool_service.RetrieveToolSchemaResponse.deserialize, + ) + return self._stubs["retrieve_tool_schema"] + + @property + def retrieve_tools( + self, + ) -> Callable[ + [tool_service.RetrieveToolsRequest], tool_service.RetrieveToolsResponse + ]: + r"""Return a callable for the retrieve tools method over gRPC. + + Retrieve the list of tools included in the specified + toolset. + + Returns: + Callable[[~.RetrieveToolsRequest], + ~.RetrieveToolsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "retrieve_tools" not in self._stubs: + self._stubs["retrieve_tools"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.ToolService/RetrieveTools", + request_serializer=tool_service.RetrieveToolsRequest.serialize, + response_deserializer=tool_service.RetrieveToolsResponse.deserialize, + ) + return self._stubs["retrieve_tools"] + + def close(self): + self._logged_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("ToolServiceGrpcTransport",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/tool_service/transports/grpc_asyncio.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/tool_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..317522e3ed8d --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/tool_service/transports/grpc_asyncio.py @@ -0,0 +1,591 @@ +# -*- coding: utf-8 -*- +# 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. +# +import inspect +import json +import logging as std_logging +import pickle +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +from grpc.experimental import aio # type: ignore + +from google.cloud.ces_v1beta.types import tool_service + +from .base import DEFAULT_CLIENT_INFO, ToolServiceTransport +from .grpc import ToolServiceGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.ces.v1beta.ToolService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.ces.v1beta.ToolService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class ToolServiceGrpcAsyncIOTransport(ToolServiceTransport): + """gRPC AsyncIO backend transport for ToolService. + + Tool service provides APIs for interacting with CES tools. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "ces.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "ces.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'ces.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def execute_tool( + self, + ) -> Callable[ + [tool_service.ExecuteToolRequest], Awaitable[tool_service.ExecuteToolResponse] + ]: + r"""Return a callable for the execute tool method over gRPC. + + Executes the given tool with the given arguments. + + Returns: + Callable[[~.ExecuteToolRequest], + Awaitable[~.ExecuteToolResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "execute_tool" not in self._stubs: + self._stubs["execute_tool"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.ToolService/ExecuteTool", + request_serializer=tool_service.ExecuteToolRequest.serialize, + response_deserializer=tool_service.ExecuteToolResponse.deserialize, + ) + return self._stubs["execute_tool"] + + @property + def retrieve_tool_schema( + self, + ) -> Callable[ + [tool_service.RetrieveToolSchemaRequest], + Awaitable[tool_service.RetrieveToolSchemaResponse], + ]: + r"""Return a callable for the retrieve tool schema method over gRPC. + + Retrieve the schema of the given tool. The schema is + computed on the fly for the given instance of the tool. + + Returns: + Callable[[~.RetrieveToolSchemaRequest], + Awaitable[~.RetrieveToolSchemaResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "retrieve_tool_schema" not in self._stubs: + self._stubs["retrieve_tool_schema"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.ToolService/RetrieveToolSchema", + request_serializer=tool_service.RetrieveToolSchemaRequest.serialize, + response_deserializer=tool_service.RetrieveToolSchemaResponse.deserialize, + ) + return self._stubs["retrieve_tool_schema"] + + @property + def retrieve_tools( + self, + ) -> Callable[ + [tool_service.RetrieveToolsRequest], + Awaitable[tool_service.RetrieveToolsResponse], + ]: + r"""Return a callable for the retrieve tools method over gRPC. + + Retrieve the list of tools included in the specified + toolset. + + Returns: + Callable[[~.RetrieveToolsRequest], + Awaitable[~.RetrieveToolsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "retrieve_tools" not in self._stubs: + self._stubs["retrieve_tools"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.ToolService/RetrieveTools", + request_serializer=tool_service.RetrieveToolsRequest.serialize, + response_deserializer=tool_service.RetrieveToolsResponse.deserialize, + ) + return self._stubs["retrieve_tools"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.execute_tool: self._wrap_method( + self.execute_tool, + default_timeout=None, + client_info=client_info, + ), + self.retrieve_tool_schema: self._wrap_method( + self.retrieve_tool_schema, + default_timeout=None, + client_info=client_info, + ), + self.retrieve_tools: self._wrap_method( + self.retrieve_tools, + default_timeout=None, + client_info=client_info, + ), + self.get_location: self._wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: self._wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + +__all__ = ("ToolServiceGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/tool_service/transports/rest.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/tool_service/transports/rest.py new file mode 100644 index 000000000000..144584b733a3 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/tool_service/transports/rest.py @@ -0,0 +1,1807 @@ +# -*- coding: utf-8 -*- +# 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. +# +import dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.ces_v1beta.types import tool_service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseToolServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class ToolServiceRestInterceptor: + """Interceptor for ToolService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the ToolServiceRestTransport. + + .. code-block:: python + class MyCustomToolServiceInterceptor(ToolServiceRestInterceptor): + def pre_execute_tool(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_execute_tool(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_retrieve_tools(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_retrieve_tools(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_retrieve_tool_schema(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_retrieve_tool_schema(self, response): + logging.log(f"Received response: {response}") + return response + + transport = ToolServiceRestTransport(interceptor=MyCustomToolServiceInterceptor()) + client = ToolServiceClient(transport=transport) + + + """ + + def pre_execute_tool( + self, + request: tool_service.ExecuteToolRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + tool_service.ExecuteToolRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for execute_tool + + Override in a subclass to manipulate the request or metadata + before they are sent to the ToolService server. + """ + return request, metadata + + def post_execute_tool( + self, response: tool_service.ExecuteToolResponse + ) -> tool_service.ExecuteToolResponse: + """Post-rpc interceptor for execute_tool + + DEPRECATED. Please use the `post_execute_tool_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ToolService server but before + it is returned to user code. This `post_execute_tool` interceptor runs + before the `post_execute_tool_with_metadata` interceptor. + """ + return response + + def post_execute_tool_with_metadata( + self, + response: tool_service.ExecuteToolResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + tool_service.ExecuteToolResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for execute_tool + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ToolService server but before it is returned to user code. + + We recommend only using this `post_execute_tool_with_metadata` + interceptor in new development instead of the `post_execute_tool` interceptor. + When both interceptors are used, this `post_execute_tool_with_metadata` interceptor runs after the + `post_execute_tool` interceptor. The (possibly modified) response returned by + `post_execute_tool` will be passed to + `post_execute_tool_with_metadata`. + """ + return response, metadata + + def pre_retrieve_tools( + self, + request: tool_service.RetrieveToolsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + tool_service.RetrieveToolsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for retrieve_tools + + Override in a subclass to manipulate the request or metadata + before they are sent to the ToolService server. + """ + return request, metadata + + def post_retrieve_tools( + self, response: tool_service.RetrieveToolsResponse + ) -> tool_service.RetrieveToolsResponse: + """Post-rpc interceptor for retrieve_tools + + DEPRECATED. Please use the `post_retrieve_tools_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ToolService server but before + it is returned to user code. This `post_retrieve_tools` interceptor runs + before the `post_retrieve_tools_with_metadata` interceptor. + """ + return response + + def post_retrieve_tools_with_metadata( + self, + response: tool_service.RetrieveToolsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + tool_service.RetrieveToolsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for retrieve_tools + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ToolService server but before it is returned to user code. + + We recommend only using this `post_retrieve_tools_with_metadata` + interceptor in new development instead of the `post_retrieve_tools` interceptor. + When both interceptors are used, this `post_retrieve_tools_with_metadata` interceptor runs after the + `post_retrieve_tools` interceptor. The (possibly modified) response returned by + `post_retrieve_tools` will be passed to + `post_retrieve_tools_with_metadata`. + """ + return response, metadata + + def pre_retrieve_tool_schema( + self, + request: tool_service.RetrieveToolSchemaRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + tool_service.RetrieveToolSchemaRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for retrieve_tool_schema + + Override in a subclass to manipulate the request or metadata + before they are sent to the ToolService server. + """ + return request, metadata + + def post_retrieve_tool_schema( + self, response: tool_service.RetrieveToolSchemaResponse + ) -> tool_service.RetrieveToolSchemaResponse: + """Post-rpc interceptor for retrieve_tool_schema + + DEPRECATED. Please use the `post_retrieve_tool_schema_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ToolService server but before + it is returned to user code. This `post_retrieve_tool_schema` interceptor runs + before the `post_retrieve_tool_schema_with_metadata` interceptor. + """ + return response + + def post_retrieve_tool_schema_with_metadata( + self, + response: tool_service.RetrieveToolSchemaResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + tool_service.RetrieveToolSchemaResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for retrieve_tool_schema + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ToolService server but before it is returned to user code. + + We recommend only using this `post_retrieve_tool_schema_with_metadata` + interceptor in new development instead of the `post_retrieve_tool_schema` interceptor. + When both interceptors are used, this `post_retrieve_tool_schema_with_metadata` interceptor runs after the + `post_retrieve_tool_schema` interceptor. The (possibly modified) response returned by + `post_retrieve_tool_schema` will be passed to + `post_retrieve_tool_schema_with_metadata`. + """ + return response, metadata + + def pre_get_location( + self, + request: locations_pb2.GetLocationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the ToolService server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.Location + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the ToolService server but before + it is returned to user code. + """ + return response + + def pre_list_locations( + self, + request: locations_pb2.ListLocationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the ToolService server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsResponse + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the ToolService server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the ToolService server. + """ + return request, metadata + + def post_cancel_operation(self, response: None) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the ToolService server but before + it is returned to user code. + """ + return response + + def pre_delete_operation( + self, + request: operations_pb2.DeleteOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the ToolService server. + """ + return request, metadata + + def post_delete_operation(self, response: None) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the ToolService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the ToolService server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the ToolService server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the ToolService server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the ToolService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class ToolServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ToolServiceRestInterceptor + + +class ToolServiceRestTransport(_BaseToolServiceRestTransport): + """REST backend synchronous transport for ToolService. + + Tool service provides APIs for interacting with CES tools. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "ces.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[ToolServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'ces.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or ToolServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _ExecuteTool( + _BaseToolServiceRestTransport._BaseExecuteTool, ToolServiceRestStub + ): + def __hash__(self): + return hash("ToolServiceRestTransport.ExecuteTool") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: tool_service.ExecuteToolRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> tool_service.ExecuteToolResponse: + r"""Call the execute tool method over HTTP. + + Args: + request (~.tool_service.ExecuteToolRequest): + The request object. Request message for + [ToolService.ExecuteTool][google.cloud.ces.v1beta.ToolService.ExecuteTool]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.tool_service.ExecuteToolResponse: + Response message for + [ToolService.ExecuteTool][google.cloud.ces.v1beta.ToolService.ExecuteTool]. + + """ + + http_options = ( + _BaseToolServiceRestTransport._BaseExecuteTool._get_http_options() + ) + + request, metadata = self._interceptor.pre_execute_tool(request, metadata) + transcoded_request = ( + _BaseToolServiceRestTransport._BaseExecuteTool._get_transcoded_request( + http_options, request + ) + ) + + body = ( + _BaseToolServiceRestTransport._BaseExecuteTool._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseToolServiceRestTransport._BaseExecuteTool._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.ToolServiceClient.ExecuteTool", + extra={ + "serviceName": "google.cloud.ces.v1beta.ToolService", + "rpcName": "ExecuteTool", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ToolServiceRestTransport._ExecuteTool._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = tool_service.ExecuteToolResponse() + pb_resp = tool_service.ExecuteToolResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_execute_tool(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_execute_tool_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = tool_service.ExecuteToolResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.ToolServiceClient.execute_tool", + extra={ + "serviceName": "google.cloud.ces.v1beta.ToolService", + "rpcName": "ExecuteTool", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _RetrieveTools( + _BaseToolServiceRestTransport._BaseRetrieveTools, ToolServiceRestStub + ): + def __hash__(self): + return hash("ToolServiceRestTransport.RetrieveTools") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: tool_service.RetrieveToolsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> tool_service.RetrieveToolsResponse: + r"""Call the retrieve tools method over HTTP. + + Args: + request (~.tool_service.RetrieveToolsRequest): + The request object. Request message for + [ToolService.RetrieveTools][google.cloud.ces.v1beta.ToolService.RetrieveTools]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.tool_service.RetrieveToolsResponse: + Response message for + [ToolService.RetrieveTools][google.cloud.ces.v1beta.ToolService.RetrieveTools]. + + """ + + http_options = ( + _BaseToolServiceRestTransport._BaseRetrieveTools._get_http_options() + ) + + request, metadata = self._interceptor.pre_retrieve_tools(request, metadata) + transcoded_request = _BaseToolServiceRestTransport._BaseRetrieveTools._get_transcoded_request( + http_options, request + ) + + body = ( + _BaseToolServiceRestTransport._BaseRetrieveTools._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseToolServiceRestTransport._BaseRetrieveTools._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.ToolServiceClient.RetrieveTools", + extra={ + "serviceName": "google.cloud.ces.v1beta.ToolService", + "rpcName": "RetrieveTools", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ToolServiceRestTransport._RetrieveTools._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = tool_service.RetrieveToolsResponse() + pb_resp = tool_service.RetrieveToolsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_retrieve_tools(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_retrieve_tools_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = tool_service.RetrieveToolsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.ToolServiceClient.retrieve_tools", + extra={ + "serviceName": "google.cloud.ces.v1beta.ToolService", + "rpcName": "RetrieveTools", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _RetrieveToolSchema( + _BaseToolServiceRestTransport._BaseRetrieveToolSchema, ToolServiceRestStub + ): + def __hash__(self): + return hash("ToolServiceRestTransport.RetrieveToolSchema") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: tool_service.RetrieveToolSchemaRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> tool_service.RetrieveToolSchemaResponse: + r"""Call the retrieve tool schema method over HTTP. + + Args: + request (~.tool_service.RetrieveToolSchemaRequest): + The request object. Request message for + [ToolService.RetrieveToolSchema][google.cloud.ces.v1beta.ToolService.RetrieveToolSchema]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.tool_service.RetrieveToolSchemaResponse: + Response message for + [ToolService.RetrieveToolSchema][google.cloud.ces.v1beta.ToolService.RetrieveToolSchema]. + + """ + + http_options = _BaseToolServiceRestTransport._BaseRetrieveToolSchema._get_http_options() + + request, metadata = self._interceptor.pre_retrieve_tool_schema( + request, metadata + ) + transcoded_request = _BaseToolServiceRestTransport._BaseRetrieveToolSchema._get_transcoded_request( + http_options, request + ) + + body = _BaseToolServiceRestTransport._BaseRetrieveToolSchema._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseToolServiceRestTransport._BaseRetrieveToolSchema._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.ToolServiceClient.RetrieveToolSchema", + extra={ + "serviceName": "google.cloud.ces.v1beta.ToolService", + "rpcName": "RetrieveToolSchema", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ToolServiceRestTransport._RetrieveToolSchema._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = tool_service.RetrieveToolSchemaResponse() + pb_resp = tool_service.RetrieveToolSchemaResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_retrieve_tool_schema(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_retrieve_tool_schema_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = tool_service.RetrieveToolSchemaResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.ToolServiceClient.retrieve_tool_schema", + extra={ + "serviceName": "google.cloud.ces.v1beta.ToolService", + "rpcName": "RetrieveToolSchema", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def execute_tool( + self, + ) -> Callable[[tool_service.ExecuteToolRequest], tool_service.ExecuteToolResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ExecuteTool(self._session, self._host, self._interceptor) # type: ignore + + @property + def retrieve_tools( + self, + ) -> Callable[ + [tool_service.RetrieveToolsRequest], tool_service.RetrieveToolsResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RetrieveTools(self._session, self._host, self._interceptor) # type: ignore + + @property + def retrieve_tool_schema( + self, + ) -> Callable[ + [tool_service.RetrieveToolSchemaRequest], + tool_service.RetrieveToolSchemaResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RetrieveToolSchema(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation( + _BaseToolServiceRestTransport._BaseGetLocation, ToolServiceRestStub + ): + def __hash__(self): + return hash("ToolServiceRestTransport.GetLocation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: locations_pb2.GetLocationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options = ( + _BaseToolServiceRestTransport._BaseGetLocation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_location(request, metadata) + transcoded_request = ( + _BaseToolServiceRestTransport._BaseGetLocation._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseToolServiceRestTransport._BaseGetLocation._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.ToolServiceClient.GetLocation", + extra={ + "serviceName": "google.cloud.ces.v1beta.ToolService", + "rpcName": "GetLocation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ToolServiceRestTransport._GetLocation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.Location() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_location(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.ToolServiceAsyncClient.GetLocation", + extra={ + "serviceName": "google.cloud.ces.v1beta.ToolService", + "rpcName": "GetLocation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations( + _BaseToolServiceRestTransport._BaseListLocations, ToolServiceRestStub + ): + def __hash__(self): + return hash("ToolServiceRestTransport.ListLocations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: locations_pb2.ListLocationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options = ( + _BaseToolServiceRestTransport._BaseListLocations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + transcoded_request = _BaseToolServiceRestTransport._BaseListLocations._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = ( + _BaseToolServiceRestTransport._BaseListLocations._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.ToolServiceClient.ListLocations", + extra={ + "serviceName": "google.cloud.ces.v1beta.ToolService", + "rpcName": "ListLocations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ToolServiceRestTransport._ListLocations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_locations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.ToolServiceAsyncClient.ListLocations", + extra={ + "serviceName": "google.cloud.ces.v1beta.ToolService", + "rpcName": "ListLocations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation( + _BaseToolServiceRestTransport._BaseCancelOperation, ToolServiceRestStub + ): + def __hash__(self): + return hash("ToolServiceRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseToolServiceRestTransport._BaseCancelOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + transcoded_request = _BaseToolServiceRestTransport._BaseCancelOperation._get_transcoded_request( + http_options, request + ) + + body = _BaseToolServiceRestTransport._BaseCancelOperation._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseToolServiceRestTransport._BaseCancelOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.ToolServiceClient.CancelOperation", + extra={ + "serviceName": "google.cloud.ces.v1beta.ToolService", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ToolServiceRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation( + _BaseToolServiceRestTransport._BaseDeleteOperation, ToolServiceRestStub + ): + def __hash__(self): + return hash("ToolServiceRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.DeleteOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseToolServiceRestTransport._BaseDeleteOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_operation( + request, metadata + ) + transcoded_request = _BaseToolServiceRestTransport._BaseDeleteOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseToolServiceRestTransport._BaseDeleteOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.ToolServiceClient.DeleteOperation", + extra={ + "serviceName": "google.cloud.ces.v1beta.ToolService", + "rpcName": "DeleteOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ToolServiceRestTransport._DeleteOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation( + _BaseToolServiceRestTransport._BaseGetOperation, ToolServiceRestStub + ): + def __hash__(self): + return hash("ToolServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = ( + _BaseToolServiceRestTransport._BaseGetOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = ( + _BaseToolServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseToolServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.ToolServiceClient.GetOperation", + extra={ + "serviceName": "google.cloud.ces.v1beta.ToolService", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ToolServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.ToolServiceAsyncClient.GetOperation", + extra={ + "serviceName": "google.cloud.ces.v1beta.ToolService", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations( + _BaseToolServiceRestTransport._BaseListOperations, ToolServiceRestStub + ): + def __hash__(self): + return hash("ToolServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options = ( + _BaseToolServiceRestTransport._BaseListOperations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = _BaseToolServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseToolServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.ToolServiceClient.ListOperations", + extra={ + "serviceName": "google.cloud.ces.v1beta.ToolService", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ToolServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.ToolServiceAsyncClient.ListOperations", + extra={ + "serviceName": "google.cloud.ces.v1beta.ToolService", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("ToolServiceRestTransport",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/tool_service/transports/rest_base.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/tool_service/transports/rest_base.py new file mode 100644 index 000000000000..720eafaf118a --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/tool_service/transports/rest_base.py @@ -0,0 +1,420 @@ +# -*- coding: utf-8 -*- +# 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. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.ces_v1beta.types import tool_service + +from .base import DEFAULT_CLIENT_INFO, ToolServiceTransport + + +class _BaseToolServiceRestTransport(ToolServiceTransport): + """Base REST backend transport for ToolService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "ces.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'ces.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseExecuteTool: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*/apps/*}:executeTool", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = tool_service.ExecuteToolRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseToolServiceRestTransport._BaseExecuteTool._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRetrieveTools: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{toolset=projects/*/locations/*/apps/*/toolsets/*}:retrieveTools", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = tool_service.RetrieveToolsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseToolServiceRestTransport._BaseRetrieveTools._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRetrieveToolSchema: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*/apps/*}:retrieveToolSchema", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = tool_service.RetrieveToolSchemaRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseToolServiceRestTransport._BaseRetrieveToolSchema._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetLocation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListLocations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*}/locations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseToolServiceRestTransport",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/widget_service/__init__.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/widget_service/__init__.py new file mode 100644 index 000000000000..99e15a33c441 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/widget_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# 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 .async_client import WidgetServiceAsyncClient +from .client import WidgetServiceClient + +__all__ = ( + "WidgetServiceClient", + "WidgetServiceAsyncClient", +) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/widget_service/async_client.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/widget_service/async_client.py new file mode 100644 index 000000000000..b7b39d928c42 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/widget_service/async_client.py @@ -0,0 +1,735 @@ +# -*- coding: utf-8 -*- +# 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. +# +import logging as std_logging +import re +from collections import OrderedDict +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.ces_v1beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.ces_v1beta.types import widget_service + +from .client import WidgetServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, WidgetServiceTransport +from .transports.grpc_asyncio import WidgetServiceGrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class WidgetServiceAsyncClient: + """Provides APIs for widgets to interact with CES APIs.""" + + _client: WidgetServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = WidgetServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = WidgetServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = WidgetServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = WidgetServiceClient._DEFAULT_UNIVERSE + + deployment_path = staticmethod(WidgetServiceClient.deployment_path) + parse_deployment_path = staticmethod(WidgetServiceClient.parse_deployment_path) + session_path = staticmethod(WidgetServiceClient.session_path) + parse_session_path = staticmethod(WidgetServiceClient.parse_session_path) + common_billing_account_path = staticmethod( + WidgetServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + WidgetServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(WidgetServiceClient.common_folder_path) + parse_common_folder_path = staticmethod( + WidgetServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + WidgetServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + WidgetServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod(WidgetServiceClient.common_project_path) + parse_common_project_path = staticmethod( + WidgetServiceClient.parse_common_project_path + ) + common_location_path = staticmethod(WidgetServiceClient.common_location_path) + parse_common_location_path = staticmethod( + WidgetServiceClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + WidgetServiceAsyncClient: The constructed client. + """ + sa_info_func = ( + WidgetServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(WidgetServiceAsyncClient, info, *args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + WidgetServiceAsyncClient: The constructed client. + """ + sa_file_func = ( + WidgetServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(WidgetServiceAsyncClient, filename, *args, **kwargs) + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return WidgetServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> WidgetServiceTransport: + """Returns the transport used by the client instance. + + Returns: + WidgetServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = WidgetServiceClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, WidgetServiceTransport, Callable[..., WidgetServiceTransport]] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the widget service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,WidgetServiceTransport,Callable[..., WidgetServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the WidgetServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = WidgetServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.ces_v1beta.WidgetServiceAsyncClient`.", + extra={ + "serviceName": "google.cloud.ces.v1beta.WidgetService", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.cloud.ces.v1beta.WidgetService", + "credentialsType": None, + }, + ) + + async def generate_chat_token( + self, + request: Optional[Union[widget_service.GenerateChatTokenRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> widget_service.GenerateChatTokenResponse: + r"""Generates a session scoped token for chat widget to + authenticate with Session APIs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + async def sample_generate_chat_token(): + # Create a client + client = ces_v1beta.WidgetServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.GenerateChatTokenRequest( + name="name_value", + deployment="deployment_value", + ) + + # Make the request + response = await client.generate_chat_token(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.ces_v1beta.types.GenerateChatTokenRequest, dict]]): + The request object. Request message for + [WidgetService.GenerateChatToken][google.cloud.ces.v1beta.WidgetService.GenerateChatToken]. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.GenerateChatTokenResponse: + Response message for + [WidgetService.GenerateChatToken][google.cloud.ces.v1beta.WidgetService.GenerateChatToken]. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, widget_service.GenerateChatTokenRequest): + request = widget_service.GenerateChatTokenRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.generate_chat_token + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.delete_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "WidgetServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("WidgetServiceAsyncClient",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/widget_service/client.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/widget_service/client.py new file mode 100644 index 000000000000..a6f666f45acc --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/widget_service/client.py @@ -0,0 +1,1209 @@ +# -*- coding: utf-8 -*- +# 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. +# +import json +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.ces_v1beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.ces_v1beta.types import widget_service + +from .transports.base import DEFAULT_CLIENT_INFO, WidgetServiceTransport +from .transports.grpc import WidgetServiceGrpcTransport +from .transports.grpc_asyncio import WidgetServiceGrpcAsyncIOTransport +from .transports.rest import WidgetServiceRestTransport + + +class WidgetServiceClientMeta(type): + """Metaclass for the WidgetService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[WidgetServiceTransport]] + _transport_registry["grpc"] = WidgetServiceGrpcTransport + _transport_registry["grpc_asyncio"] = WidgetServiceGrpcAsyncIOTransport + _transport_registry["rest"] = WidgetServiceRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[WidgetServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class WidgetServiceClient(metaclass=WidgetServiceClientMeta): + """Provides APIs for widgets to interact with CES APIs.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "ces.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "ces.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + WidgetServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + WidgetServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> WidgetServiceTransport: + """Returns the transport used by the client instance. + + Returns: + WidgetServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def deployment_path( + project: str, + location: str, + app: str, + deployment: str, + ) -> str: + """Returns a fully-qualified deployment string.""" + return "projects/{project}/locations/{location}/apps/{app}/deployments/{deployment}".format( + project=project, + location=location, + app=app, + deployment=deployment, + ) + + @staticmethod + def parse_deployment_path(path: str) -> Dict[str, str]: + """Parses a deployment path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/apps/(?P.+?)/deployments/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def session_path( + project: str, + location: str, + app: str, + session: str, + ) -> str: + """Returns a fully-qualified session string.""" + return "projects/{project}/locations/{location}/apps/{app}/sessions/{session}".format( + project=project, + location=location, + app=app, + session=session, + ) + + @staticmethod + def parse_session_path(path: str) -> Dict[str, str]: + """Parses a session path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/apps/(?P.+?)/sessions/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = WidgetServiceClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = WidgetServiceClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = WidgetServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = WidgetServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = WidgetServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = WidgetServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, WidgetServiceTransport, Callable[..., WidgetServiceTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the widget service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,WidgetServiceTransport,Callable[..., WidgetServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the WidgetServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + WidgetServiceClient._read_environment_variables() + ) + self._client_cert_source = WidgetServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = WidgetServiceClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, WidgetServiceTransport) + if transport_provided: + # transport is a WidgetServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(WidgetServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or WidgetServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[WidgetServiceTransport], Callable[..., WidgetServiceTransport] + ] = ( + WidgetServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., WidgetServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.ces_v1beta.WidgetServiceClient`.", + extra={ + "serviceName": "google.cloud.ces.v1beta.WidgetService", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.cloud.ces.v1beta.WidgetService", + "credentialsType": None, + }, + ) + + def generate_chat_token( + self, + request: Optional[Union[widget_service.GenerateChatTokenRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> widget_service.GenerateChatTokenResponse: + r"""Generates a session scoped token for chat widget to + authenticate with Session APIs. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import ces_v1beta + + def sample_generate_chat_token(): + # Create a client + client = ces_v1beta.WidgetServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.GenerateChatTokenRequest( + name="name_value", + deployment="deployment_value", + ) + + # Make the request + response = client.generate_chat_token(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.ces_v1beta.types.GenerateChatTokenRequest, dict]): + The request object. Request message for + [WidgetService.GenerateChatToken][google.cloud.ces.v1beta.WidgetService.GenerateChatToken]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.ces_v1beta.types.GenerateChatTokenResponse: + Response message for + [WidgetService.GenerateChatToken][google.cloud.ces.v1beta.WidgetService.GenerateChatToken]. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, widget_service.GenerateChatTokenRequest): + request = widget_service.GenerateChatTokenRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.generate_chat_token] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "WidgetServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("WidgetServiceClient",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/widget_service/transports/README.rst b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/widget_service/transports/README.rst new file mode 100644 index 000000000000..2c4c750cc475 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/widget_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`WidgetServiceTransport` is the ABC for all transports. +- public child `WidgetServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `WidgetServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseWidgetServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `WidgetServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/widget_service/transports/__init__.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/widget_service/transports/__init__.py new file mode 100644 index 000000000000..573dad114270 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/widget_service/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# 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 collections import OrderedDict +from typing import Dict, Type + +from .base import WidgetServiceTransport +from .grpc import WidgetServiceGrpcTransport +from .grpc_asyncio import WidgetServiceGrpcAsyncIOTransport +from .rest import WidgetServiceRestInterceptor, WidgetServiceRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[WidgetServiceTransport]] +_transport_registry["grpc"] = WidgetServiceGrpcTransport +_transport_registry["grpc_asyncio"] = WidgetServiceGrpcAsyncIOTransport +_transport_registry["rest"] = WidgetServiceRestTransport + +__all__ = ( + "WidgetServiceTransport", + "WidgetServiceGrpcTransport", + "WidgetServiceGrpcAsyncIOTransport", + "WidgetServiceRestTransport", + "WidgetServiceRestInterceptor", +) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/widget_service/transports/base.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/widget_service/transports/base.py new file mode 100644 index 000000000000..e30a8b58c304 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/widget_service/transports/base.py @@ -0,0 +1,267 @@ +# -*- coding: utf-8 -*- +# 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. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +import google.auth # type: ignore +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.ces_v1beta import gapic_version as package_version +from google.cloud.ces_v1beta.types import widget_service + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class WidgetServiceTransport(abc.ABC): + """Abstract transport class for WidgetService.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/ces", + "https://www.googleapis.com/auth/cloud-platform", + ) + + DEFAULT_HOST: str = "ces.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'ces.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.generate_chat_token: gapic_v1.method.wrap_method( + self.generate_chat_token, + default_timeout=None, + client_info=client_info, + ), + self.get_location: gapic_v1.method.wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: gapic_v1.method.wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: gapic_v1.method.wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def generate_chat_token( + self, + ) -> Callable[ + [widget_service.GenerateChatTokenRequest], + Union[ + widget_service.GenerateChatTokenResponse, + Awaitable[widget_service.GenerateChatTokenResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[ + [operations_pb2.DeleteOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def get_location( + self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[ + locations_pb2.ListLocationsResponse, + Awaitable[locations_pb2.ListLocationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("WidgetServiceTransport",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/widget_service/transports/grpc.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/widget_service/transports/grpc.py new file mode 100644 index 000000000000..211751ae6b22 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/widget_service/transports/grpc.py @@ -0,0 +1,470 @@ +# -*- coding: utf-8 -*- +# 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. +# +import json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson + +from google.cloud.ces_v1beta.types import widget_service + +from .base import DEFAULT_CLIENT_INFO, WidgetServiceTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.ces.v1beta.WidgetService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.ces.v1beta.WidgetService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class WidgetServiceGrpcTransport(WidgetServiceTransport): + """gRPC backend transport for WidgetService. + + Provides APIs for widgets to interact with CES APIs. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "ces.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'ces.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "ces.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def generate_chat_token( + self, + ) -> Callable[ + [widget_service.GenerateChatTokenRequest], + widget_service.GenerateChatTokenResponse, + ]: + r"""Return a callable for the generate chat token method over gRPC. + + Generates a session scoped token for chat widget to + authenticate with Session APIs. + + Returns: + Callable[[~.GenerateChatTokenRequest], + ~.GenerateChatTokenResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "generate_chat_token" not in self._stubs: + self._stubs["generate_chat_token"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.WidgetService/GenerateChatToken", + request_serializer=widget_service.GenerateChatTokenRequest.serialize, + response_deserializer=widget_service.GenerateChatTokenResponse.deserialize, + ) + return self._stubs["generate_chat_token"] + + def close(self): + self._logged_channel.close() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("WidgetServiceGrpcTransport",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/widget_service/transports/grpc_asyncio.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/widget_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..929f85ed1f6f --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/widget_service/transports/grpc_asyncio.py @@ -0,0 +1,523 @@ +# -*- coding: utf-8 -*- +# 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. +# +import inspect +import json +import logging as std_logging +import pickle +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +from grpc.experimental import aio # type: ignore + +from google.cloud.ces_v1beta.types import widget_service + +from .base import DEFAULT_CLIENT_INFO, WidgetServiceTransport +from .grpc import WidgetServiceGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.ces.v1beta.WidgetService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.ces.v1beta.WidgetService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class WidgetServiceGrpcAsyncIOTransport(WidgetServiceTransport): + """gRPC AsyncIO backend transport for WidgetService. + + Provides APIs for widgets to interact with CES APIs. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "ces.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "ces.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'ces.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def generate_chat_token( + self, + ) -> Callable[ + [widget_service.GenerateChatTokenRequest], + Awaitable[widget_service.GenerateChatTokenResponse], + ]: + r"""Return a callable for the generate chat token method over gRPC. + + Generates a session scoped token for chat widget to + authenticate with Session APIs. + + Returns: + Callable[[~.GenerateChatTokenRequest], + Awaitable[~.GenerateChatTokenResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "generate_chat_token" not in self._stubs: + self._stubs["generate_chat_token"] = self._logged_channel.unary_unary( + "/google.cloud.ces.v1beta.WidgetService/GenerateChatToken", + request_serializer=widget_service.GenerateChatTokenRequest.serialize, + response_deserializer=widget_service.GenerateChatTokenResponse.deserialize, + ) + return self._stubs["generate_chat_token"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.generate_chat_token: self._wrap_method( + self.generate_chat_token, + default_timeout=None, + client_info=client_info, + ), + self.get_location: self._wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: self._wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.delete_operation: self._wrap_method( + self.delete_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self._logged_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + +__all__ = ("WidgetServiceGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/widget_service/transports/rest.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/widget_service/transports/rest.py new file mode 100644 index 000000000000..4edc6e54f514 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/widget_service/transports/rest.py @@ -0,0 +1,1346 @@ +# -*- coding: utf-8 -*- +# 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. +# +import dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.ces_v1beta.types import widget_service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseWidgetServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class WidgetServiceRestInterceptor: + """Interceptor for WidgetService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the WidgetServiceRestTransport. + + .. code-block:: python + class MyCustomWidgetServiceInterceptor(WidgetServiceRestInterceptor): + def pre_generate_chat_token(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_generate_chat_token(self, response): + logging.log(f"Received response: {response}") + return response + + transport = WidgetServiceRestTransport(interceptor=MyCustomWidgetServiceInterceptor()) + client = WidgetServiceClient(transport=transport) + + + """ + + def pre_generate_chat_token( + self, + request: widget_service.GenerateChatTokenRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + widget_service.GenerateChatTokenRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for generate_chat_token + + Override in a subclass to manipulate the request or metadata + before they are sent to the WidgetService server. + """ + return request, metadata + + def post_generate_chat_token( + self, response: widget_service.GenerateChatTokenResponse + ) -> widget_service.GenerateChatTokenResponse: + """Post-rpc interceptor for generate_chat_token + + DEPRECATED. Please use the `post_generate_chat_token_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the WidgetService server but before + it is returned to user code. This `post_generate_chat_token` interceptor runs + before the `post_generate_chat_token_with_metadata` interceptor. + """ + return response + + def post_generate_chat_token_with_metadata( + self, + response: widget_service.GenerateChatTokenResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + widget_service.GenerateChatTokenResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for generate_chat_token + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the WidgetService server but before it is returned to user code. + + We recommend only using this `post_generate_chat_token_with_metadata` + interceptor in new development instead of the `post_generate_chat_token` interceptor. + When both interceptors are used, this `post_generate_chat_token_with_metadata` interceptor runs after the + `post_generate_chat_token` interceptor. The (possibly modified) response returned by + `post_generate_chat_token` will be passed to + `post_generate_chat_token_with_metadata`. + """ + return response, metadata + + def pre_get_location( + self, + request: locations_pb2.GetLocationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the WidgetService server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.Location + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the WidgetService server but before + it is returned to user code. + """ + return response + + def pre_list_locations( + self, + request: locations_pb2.ListLocationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the WidgetService server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsResponse + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the WidgetService server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the WidgetService server. + """ + return request, metadata + + def post_cancel_operation(self, response: None) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the WidgetService server but before + it is returned to user code. + """ + return response + + def pre_delete_operation( + self, + request: operations_pb2.DeleteOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the WidgetService server. + """ + return request, metadata + + def post_delete_operation(self, response: None) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the WidgetService server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the WidgetService server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the WidgetService server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the WidgetService server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the WidgetService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class WidgetServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: WidgetServiceRestInterceptor + + +class WidgetServiceRestTransport(_BaseWidgetServiceRestTransport): + """REST backend synchronous transport for WidgetService. + + Provides APIs for widgets to interact with CES APIs. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "ces.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[WidgetServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'ces.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or WidgetServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _GenerateChatToken( + _BaseWidgetServiceRestTransport._BaseGenerateChatToken, WidgetServiceRestStub + ): + def __hash__(self): + return hash("WidgetServiceRestTransport.GenerateChatToken") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: widget_service.GenerateChatTokenRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> widget_service.GenerateChatTokenResponse: + r"""Call the generate chat token method over HTTP. + + Args: + request (~.widget_service.GenerateChatTokenRequest): + The request object. Request message for + [WidgetService.GenerateChatToken][google.cloud.ces.v1beta.WidgetService.GenerateChatToken]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.widget_service.GenerateChatTokenResponse: + Response message for + [WidgetService.GenerateChatToken][google.cloud.ces.v1beta.WidgetService.GenerateChatToken]. + + """ + + http_options = _BaseWidgetServiceRestTransport._BaseGenerateChatToken._get_http_options() + + request, metadata = self._interceptor.pre_generate_chat_token( + request, metadata + ) + transcoded_request = _BaseWidgetServiceRestTransport._BaseGenerateChatToken._get_transcoded_request( + http_options, request + ) + + body = _BaseWidgetServiceRestTransport._BaseGenerateChatToken._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseWidgetServiceRestTransport._BaseGenerateChatToken._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.WidgetServiceClient.GenerateChatToken", + extra={ + "serviceName": "google.cloud.ces.v1beta.WidgetService", + "rpcName": "GenerateChatToken", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = WidgetServiceRestTransport._GenerateChatToken._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = widget_service.GenerateChatTokenResponse() + pb_resp = widget_service.GenerateChatTokenResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_generate_chat_token(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_generate_chat_token_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = widget_service.GenerateChatTokenResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.WidgetServiceClient.generate_chat_token", + extra={ + "serviceName": "google.cloud.ces.v1beta.WidgetService", + "rpcName": "GenerateChatToken", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def generate_chat_token( + self, + ) -> Callable[ + [widget_service.GenerateChatTokenRequest], + widget_service.GenerateChatTokenResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GenerateChatToken(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation( + _BaseWidgetServiceRestTransport._BaseGetLocation, WidgetServiceRestStub + ): + def __hash__(self): + return hash("WidgetServiceRestTransport.GetLocation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: locations_pb2.GetLocationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.Location: + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options = ( + _BaseWidgetServiceRestTransport._BaseGetLocation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_location(request, metadata) + transcoded_request = _BaseWidgetServiceRestTransport._BaseGetLocation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = ( + _BaseWidgetServiceRestTransport._BaseGetLocation._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.WidgetServiceClient.GetLocation", + extra={ + "serviceName": "google.cloud.ces.v1beta.WidgetService", + "rpcName": "GetLocation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = WidgetServiceRestTransport._GetLocation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.Location() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_location(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.WidgetServiceAsyncClient.GetLocation", + extra={ + "serviceName": "google.cloud.ces.v1beta.WidgetService", + "rpcName": "GetLocation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations( + _BaseWidgetServiceRestTransport._BaseListLocations, WidgetServiceRestStub + ): + def __hash__(self): + return hash("WidgetServiceRestTransport.ListLocations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: locations_pb2.ListLocationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options = ( + _BaseWidgetServiceRestTransport._BaseListLocations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + transcoded_request = _BaseWidgetServiceRestTransport._BaseListLocations._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseWidgetServiceRestTransport._BaseListLocations._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.WidgetServiceClient.ListLocations", + extra={ + "serviceName": "google.cloud.ces.v1beta.WidgetService", + "rpcName": "ListLocations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = WidgetServiceRestTransport._ListLocations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_locations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.WidgetServiceAsyncClient.ListLocations", + extra={ + "serviceName": "google.cloud.ces.v1beta.WidgetService", + "rpcName": "ListLocations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation( + _BaseWidgetServiceRestTransport._BaseCancelOperation, WidgetServiceRestStub + ): + def __hash__(self): + return hash("WidgetServiceRestTransport.CancelOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseWidgetServiceRestTransport._BaseCancelOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + transcoded_request = _BaseWidgetServiceRestTransport._BaseCancelOperation._get_transcoded_request( + http_options, request + ) + + body = _BaseWidgetServiceRestTransport._BaseCancelOperation._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseWidgetServiceRestTransport._BaseCancelOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.WidgetServiceClient.CancelOperation", + extra={ + "serviceName": "google.cloud.ces.v1beta.WidgetService", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = WidgetServiceRestTransport._CancelOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_cancel_operation(None) + + @property + def delete_operation(self): + return self._DeleteOperation(self._session, self._host, self._interceptor) # type: ignore + + class _DeleteOperation( + _BaseWidgetServiceRestTransport._BaseDeleteOperation, WidgetServiceRestStub + ): + def __hash__(self): + return hash("WidgetServiceRestTransport.DeleteOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.DeleteOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Call the delete operation method over HTTP. + + Args: + request (operations_pb2.DeleteOperationRequest): + The request object for DeleteOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseWidgetServiceRestTransport._BaseDeleteOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_operation( + request, metadata + ) + transcoded_request = _BaseWidgetServiceRestTransport._BaseDeleteOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseWidgetServiceRestTransport._BaseDeleteOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.WidgetServiceClient.DeleteOperation", + extra={ + "serviceName": "google.cloud.ces.v1beta.WidgetService", + "rpcName": "DeleteOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = WidgetServiceRestTransport._DeleteOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + return self._interceptor.post_delete_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation( + _BaseWidgetServiceRestTransport._BaseGetOperation, WidgetServiceRestStub + ): + def __hash__(self): + return hash("WidgetServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options = ( + _BaseWidgetServiceRestTransport._BaseGetOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseWidgetServiceRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseWidgetServiceRestTransport._BaseGetOperation._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.WidgetServiceClient.GetOperation", + extra={ + "serviceName": "google.cloud.ces.v1beta.WidgetService", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = WidgetServiceRestTransport._GetOperation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.WidgetServiceAsyncClient.GetOperation", + extra={ + "serviceName": "google.cloud.ces.v1beta.WidgetService", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations( + _BaseWidgetServiceRestTransport._BaseListOperations, WidgetServiceRestStub + ): + def __hash__(self): + return hash("WidgetServiceRestTransport.ListOperations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + operations_pb2.ListOperationsResponse: Response from ListOperations method. + """ + + http_options = ( + _BaseWidgetServiceRestTransport._BaseListOperations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = _BaseWidgetServiceRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseWidgetServiceRestTransport._BaseListOperations._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.ces_v1beta.WidgetServiceClient.ListOperations", + extra={ + "serviceName": "google.cloud.ces.v1beta.WidgetService", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = WidgetServiceRestTransport._ListOperations._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.ces_v1beta.WidgetServiceAsyncClient.ListOperations", + extra={ + "serviceName": "google.cloud.ces.v1beta.WidgetService", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("WidgetServiceRestTransport",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/services/widget_service/transports/rest_base.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/widget_service/transports/rest_base.py new file mode 100644 index 000000000000..fe8c2f10ed0c --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/services/widget_service/transports/rest_base.py @@ -0,0 +1,306 @@ +# -*- coding: utf-8 -*- +# 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. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.ces_v1beta.types import widget_service + +from .base import DEFAULT_CLIENT_INFO, WidgetServiceTransport + + +class _BaseWidgetServiceRestTransport(WidgetServiceTransport): + """Base REST backend transport for WidgetService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "ces.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'ces.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseGenerateChatToken: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/apps/*/sessions/*}:generateChatToken", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = widget_service.GenerateChatTokenRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseWidgetServiceRestTransport._BaseGenerateChatToken._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetLocation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListLocations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*}/locations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseDeleteOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*}/operations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseWidgetServiceRestTransport",) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/__init__.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/__init__.py new file mode 100644 index 000000000000..4c31d8054ab0 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/__init__.py @@ -0,0 +1,556 @@ +# -*- coding: utf-8 -*- +# 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 .agent import ( + Agent, +) +from .agent_service import ( + BatchDeleteConversationsRequest, + BatchDeleteConversationsResponse, + CreateAgentRequest, + CreateAppRequest, + CreateAppVersionRequest, + CreateDeploymentRequest, + CreateExampleRequest, + CreateGuardrailRequest, + CreateToolRequest, + CreateToolsetRequest, + DeleteAgentRequest, + DeleteAppRequest, + DeleteAppVersionRequest, + DeleteConversationRequest, + DeleteDeploymentRequest, + DeleteExampleRequest, + DeleteGuardrailRequest, + DeleteToolRequest, + DeleteToolsetRequest, + ExportAppRequest, + ExportAppResponse, + GenerateAppResourceResponse, + GetAgentRequest, + GetAppRequest, + GetAppVersionRequest, + GetChangelogRequest, + GetConversationRequest, + GetDeploymentRequest, + GetExampleRequest, + GetGuardrailRequest, + GetToolRequest, + GetToolsetRequest, + ImportAppRequest, + ImportAppResponse, + ListAgentsRequest, + ListAgentsResponse, + ListAppsRequest, + ListAppsResponse, + ListAppVersionsRequest, + ListAppVersionsResponse, + ListChangelogsRequest, + ListChangelogsResponse, + ListConversationsRequest, + ListConversationsResponse, + ListDeploymentsRequest, + ListDeploymentsResponse, + ListExamplesRequest, + ListExamplesResponse, + ListGuardrailsRequest, + ListGuardrailsResponse, + ListToolsetsRequest, + ListToolsetsResponse, + ListToolsRequest, + ListToolsResponse, + OperationMetadata, + RestoreAppVersionRequest, + RestoreAppVersionResponse, + UpdateAgentRequest, + UpdateAppRequest, + UpdateDeploymentRequest, + UpdateExampleRequest, + UpdateGuardrailRequest, + UpdateToolRequest, + UpdateToolsetRequest, +) +from .agent_transfers import ( + ExpressionCondition, + PythonCodeCondition, + TransferRule, +) +from .app import ( + AmbientSoundConfig, + App, + AudioProcessingConfig, + AudioRecordingConfig, + BargeInConfig, + ClientCertificateSettings, + CloudLoggingSettings, + ConversationLoggingSettings, + DataStoreSettings, + ErrorHandlingSettings, + EvaluationMetricsThresholds, + EvaluationPersona, + EvaluationSettings, + LanguageSettings, + LoggingSettings, + MetricAnalysisSettings, + RedactionConfig, + SynthesizeSpeechConfig, + TimeZoneSettings, +) +from .app_version import ( + AppSnapshot, + AppVersion, +) +from .auth import ( + ApiAuthentication, + ApiKeyConfig, + BearerTokenConfig, + EndUserAuthConfig, + OAuthConfig, + ServiceAccountAuthConfig, + ServiceAgentIdTokenAuthConfig, +) +from .bigquery_export import ( + BigQueryExportSettings, +) +from .changelog import ( + Changelog, +) +from .client_function import ( + ClientFunction, +) +from .common import ( + Callback, + ChannelProfile, + ExecutionType, + ModelSettings, + ServiceDirectoryConfig, + Span, + TlsConfig, + TriggerAction, +) +from .connector_tool import ( + Action, + ConnectorTool, +) +from .connector_toolset import ( + ConnectorToolset, +) +from .conversation import ( + Conversation, +) +from .data_store import ( + DataStore, +) +from .data_store_tool import ( + DataStoreTool, +) +from .deployment import ( + Deployment, +) +from .evaluation import ( + AggregatedMetrics, + Evaluation, + EvaluationConfig, + EvaluationDataset, + EvaluationErrorInfo, + EvaluationExpectation, + EvaluationResult, + EvaluationRun, + LatencyReport, + OptimizationConfig, + PersonaRunConfig, + RunEvaluationRequest, + ScheduledEvaluationRun, +) +from .evaluation_service import ( + CreateEvaluationDatasetRequest, + CreateEvaluationExpectationRequest, + CreateEvaluationRequest, + CreateScheduledEvaluationRunRequest, + DeleteEvaluationDatasetRequest, + DeleteEvaluationExpectationRequest, + DeleteEvaluationRequest, + DeleteEvaluationResultRequest, + DeleteEvaluationRunOperationMetadata, + DeleteEvaluationRunRequest, + DeleteScheduledEvaluationRunRequest, + GenerateEvaluationOperationMetadata, + GenerateEvaluationRequest, + GetEvaluationDatasetRequest, + GetEvaluationExpectationRequest, + GetEvaluationRequest, + GetEvaluationResultRequest, + GetEvaluationRunRequest, + GetScheduledEvaluationRunRequest, + ImportEvaluationsOperationMetadata, + ImportEvaluationsRequest, + ImportEvaluationsResponse, + ListEvaluationDatasetsRequest, + ListEvaluationDatasetsResponse, + ListEvaluationExpectationsRequest, + ListEvaluationExpectationsResponse, + ListEvaluationResultsRequest, + ListEvaluationResultsResponse, + ListEvaluationRunsRequest, + ListEvaluationRunsResponse, + ListEvaluationsRequest, + ListEvaluationsResponse, + ListScheduledEvaluationRunsRequest, + ListScheduledEvaluationRunsResponse, + RunEvaluationOperationMetadata, + RunEvaluationResponse, + TestPersonaVoiceRequest, + TestPersonaVoiceResponse, + UpdateEvaluationDatasetRequest, + UpdateEvaluationExpectationRequest, + UpdateEvaluationRequest, + UpdateScheduledEvaluationRunRequest, + UploadEvaluationAudioRequest, + UploadEvaluationAudioResponse, +) +from .example import ( + AgentTransfer, + Blob, + Chunk, + Example, + Image, + Message, + ToolCall, + ToolResponse, +) +from .fakes import ( + CodeBlock, + EvaluationToolCallBehaviour, + ToolFakeConfig, +) +from .file_search_tool import ( + FileSearchTool, +) +from .golden_run import ( + GoldenRunMethod, +) +from .google_search_tool import ( + GoogleSearchTool, +) +from .guardrail import ( + Guardrail, +) +from .mcp_tool import ( + McpTool, +) +from .mcp_toolset import ( + McpToolset, +) +from .omnichannel import ( + Omnichannel, + OmnichannelIntegrationConfig, +) +from .omnichannel_service import ( + OmnichannelOperationMetadata, +) +from .open_api_tool import ( + OpenApiTool, +) +from .open_api_toolset import ( + OpenApiToolset, +) +from .python_function import ( + PythonFunction, +) +from .schema import ( + Schema, +) +from .search_suggestions import ( + GoogleSearchSuggestions, + WebSearchQuery, +) +from .session_service import ( + AudioEncoding, + BidiSessionClientMessage, + BidiSessionServerMessage, + Citations, + EndSession, + Event, + GoAway, + InputAudioConfig, + InterruptionSignal, + OutputAudioConfig, + RecognitionResult, + RunSessionRequest, + RunSessionResponse, + SessionConfig, + SessionInput, + SessionOutput, + ToolCalls, + ToolResponses, +) +from .system_tool import ( + SystemTool, +) +from .tool import ( + Tool, +) +from .tool_service import ( + ExecuteToolRequest, + ExecuteToolResponse, + RetrieveToolSchemaRequest, + RetrieveToolSchemaResponse, + RetrieveToolsRequest, + RetrieveToolsResponse, +) +from .toolset import ( + Toolset, +) +from .toolset_tool import ( + ToolsetTool, +) +from .widget_service import ( + GenerateChatTokenRequest, + GenerateChatTokenResponse, +) +from .widget_tool import ( + WidgetTool, +) + +__all__ = ( + "Agent", + "BatchDeleteConversationsRequest", + "BatchDeleteConversationsResponse", + "CreateAgentRequest", + "CreateAppRequest", + "CreateAppVersionRequest", + "CreateDeploymentRequest", + "CreateExampleRequest", + "CreateGuardrailRequest", + "CreateToolRequest", + "CreateToolsetRequest", + "DeleteAgentRequest", + "DeleteAppRequest", + "DeleteAppVersionRequest", + "DeleteConversationRequest", + "DeleteDeploymentRequest", + "DeleteExampleRequest", + "DeleteGuardrailRequest", + "DeleteToolRequest", + "DeleteToolsetRequest", + "ExportAppRequest", + "ExportAppResponse", + "GenerateAppResourceResponse", + "GetAgentRequest", + "GetAppRequest", + "GetAppVersionRequest", + "GetChangelogRequest", + "GetConversationRequest", + "GetDeploymentRequest", + "GetExampleRequest", + "GetGuardrailRequest", + "GetToolRequest", + "GetToolsetRequest", + "ImportAppRequest", + "ImportAppResponse", + "ListAgentsRequest", + "ListAgentsResponse", + "ListAppsRequest", + "ListAppsResponse", + "ListAppVersionsRequest", + "ListAppVersionsResponse", + "ListChangelogsRequest", + "ListChangelogsResponse", + "ListConversationsRequest", + "ListConversationsResponse", + "ListDeploymentsRequest", + "ListDeploymentsResponse", + "ListExamplesRequest", + "ListExamplesResponse", + "ListGuardrailsRequest", + "ListGuardrailsResponse", + "ListToolsetsRequest", + "ListToolsetsResponse", + "ListToolsRequest", + "ListToolsResponse", + "OperationMetadata", + "RestoreAppVersionRequest", + "RestoreAppVersionResponse", + "UpdateAgentRequest", + "UpdateAppRequest", + "UpdateDeploymentRequest", + "UpdateExampleRequest", + "UpdateGuardrailRequest", + "UpdateToolRequest", + "UpdateToolsetRequest", + "ExpressionCondition", + "PythonCodeCondition", + "TransferRule", + "AmbientSoundConfig", + "App", + "AudioProcessingConfig", + "AudioRecordingConfig", + "BargeInConfig", + "ClientCertificateSettings", + "CloudLoggingSettings", + "ConversationLoggingSettings", + "DataStoreSettings", + "ErrorHandlingSettings", + "EvaluationMetricsThresholds", + "EvaluationPersona", + "EvaluationSettings", + "LanguageSettings", + "LoggingSettings", + "MetricAnalysisSettings", + "RedactionConfig", + "SynthesizeSpeechConfig", + "TimeZoneSettings", + "AppSnapshot", + "AppVersion", + "ApiAuthentication", + "ApiKeyConfig", + "BearerTokenConfig", + "EndUserAuthConfig", + "OAuthConfig", + "ServiceAccountAuthConfig", + "ServiceAgentIdTokenAuthConfig", + "BigQueryExportSettings", + "Changelog", + "ClientFunction", + "Callback", + "ChannelProfile", + "ModelSettings", + "ServiceDirectoryConfig", + "Span", + "TlsConfig", + "TriggerAction", + "ExecutionType", + "Action", + "ConnectorTool", + "ConnectorToolset", + "Conversation", + "DataStore", + "DataStoreTool", + "Deployment", + "AggregatedMetrics", + "Evaluation", + "EvaluationConfig", + "EvaluationDataset", + "EvaluationErrorInfo", + "EvaluationExpectation", + "EvaluationResult", + "EvaluationRun", + "LatencyReport", + "OptimizationConfig", + "PersonaRunConfig", + "RunEvaluationRequest", + "ScheduledEvaluationRun", + "CreateEvaluationDatasetRequest", + "CreateEvaluationExpectationRequest", + "CreateEvaluationRequest", + "CreateScheduledEvaluationRunRequest", + "DeleteEvaluationDatasetRequest", + "DeleteEvaluationExpectationRequest", + "DeleteEvaluationRequest", + "DeleteEvaluationResultRequest", + "DeleteEvaluationRunOperationMetadata", + "DeleteEvaluationRunRequest", + "DeleteScheduledEvaluationRunRequest", + "GenerateEvaluationOperationMetadata", + "GenerateEvaluationRequest", + "GetEvaluationDatasetRequest", + "GetEvaluationExpectationRequest", + "GetEvaluationRequest", + "GetEvaluationResultRequest", + "GetEvaluationRunRequest", + "GetScheduledEvaluationRunRequest", + "ImportEvaluationsOperationMetadata", + "ImportEvaluationsRequest", + "ImportEvaluationsResponse", + "ListEvaluationDatasetsRequest", + "ListEvaluationDatasetsResponse", + "ListEvaluationExpectationsRequest", + "ListEvaluationExpectationsResponse", + "ListEvaluationResultsRequest", + "ListEvaluationResultsResponse", + "ListEvaluationRunsRequest", + "ListEvaluationRunsResponse", + "ListEvaluationsRequest", + "ListEvaluationsResponse", + "ListScheduledEvaluationRunsRequest", + "ListScheduledEvaluationRunsResponse", + "RunEvaluationOperationMetadata", + "RunEvaluationResponse", + "TestPersonaVoiceRequest", + "TestPersonaVoiceResponse", + "UpdateEvaluationDatasetRequest", + "UpdateEvaluationExpectationRequest", + "UpdateEvaluationRequest", + "UpdateScheduledEvaluationRunRequest", + "UploadEvaluationAudioRequest", + "UploadEvaluationAudioResponse", + "AgentTransfer", + "Blob", + "Chunk", + "Example", + "Image", + "Message", + "ToolCall", + "ToolResponse", + "CodeBlock", + "ToolFakeConfig", + "EvaluationToolCallBehaviour", + "FileSearchTool", + "GoldenRunMethod", + "GoogleSearchTool", + "Guardrail", + "McpTool", + "McpToolset", + "Omnichannel", + "OmnichannelIntegrationConfig", + "OmnichannelOperationMetadata", + "OpenApiTool", + "OpenApiToolset", + "PythonFunction", + "Schema", + "GoogleSearchSuggestions", + "WebSearchQuery", + "BidiSessionClientMessage", + "BidiSessionServerMessage", + "Citations", + "EndSession", + "Event", + "GoAway", + "InputAudioConfig", + "InterruptionSignal", + "OutputAudioConfig", + "RecognitionResult", + "RunSessionRequest", + "RunSessionResponse", + "SessionConfig", + "SessionInput", + "SessionOutput", + "ToolCalls", + "ToolResponses", + "AudioEncoding", + "SystemTool", + "Tool", + "ExecuteToolRequest", + "ExecuteToolResponse", + "RetrieveToolSchemaRequest", + "RetrieveToolSchemaResponse", + "RetrieveToolsRequest", + "RetrieveToolsResponse", + "Toolset", + "ToolsetTool", + "GenerateChatTokenRequest", + "GenerateChatTokenResponse", + "WidgetTool", +) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/agent.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/agent.py new file mode 100644 index 000000000000..3d0f6f22e492 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/agent.py @@ -0,0 +1,359 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.ces_v1beta.types import agent_transfers, common + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "Agent", + }, +) + + +class Agent(proto.Message): + r"""An agent acts as the fundamental building block that provides + instructions to the Large Language Model (LLM) for executing + specific tasks. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + llm_agent (google.cloud.ces_v1beta.types.Agent.LlmAgent): + Optional. The default agent type. + + This field is a member of `oneof`_ ``agent_type``. + remote_dialogflow_agent (google.cloud.ces_v1beta.types.Agent.RemoteDialogflowAgent): + Optional. The remote + `Dialogflow `__ + agent to be used for the agent execution. If this field is + set, all other agent level properties will be ignored. + + Note: If the Dialogflow agent is in a different project from + the app, you should grant ``roles/dialogflow.client`` to the + CES service agent + ``service-@gcp-sa-ces.iam.gserviceaccount.com``. + + This field is a member of `oneof`_ ``agent_type``. + name (str): + Identifier. The unique identifier of the agent. Format: + ``projects/{project}/locations/{location}/apps/{app}/agents/{agent}`` + display_name (str): + Required. Display name of the agent. + description (str): + Optional. Human-readable description of the + agent. + model_settings (google.cloud.ces_v1beta.types.ModelSettings): + Optional. Configurations for the LLM model. + instruction (str): + Optional. Instructions for the LLM model to + guide the agent's behavior. + tools (MutableSequence[str]): + Optional. List of available tools for the agent. Format: + ``projects/{project}/locations/{location}/apps/{app}/tools/{tool}`` + child_agents (MutableSequence[str]): + Optional. List of child agents in the agent tree. Format: + ``projects/{project}/locations/{location}/apps/{app}/agents/{agent}`` + before_agent_callbacks (MutableSequence[google.cloud.ces_v1beta.types.Callback]): + Optional. The callbacks to execute before the + agent is called. The provided callbacks are + executed sequentially in the exact order they + are given in the list. If a callback returns an + overridden response, execution stops and any + remaining callbacks are skipped. + after_agent_callbacks (MutableSequence[google.cloud.ces_v1beta.types.Callback]): + Optional. The callbacks to execute after the + agent is called. The provided callbacks are + executed sequentially in the exact order they + are given in the list. If a callback returns an + overridden response, execution stops and any + remaining callbacks are skipped. + before_model_callbacks (MutableSequence[google.cloud.ces_v1beta.types.Callback]): + Optional. The callbacks to execute before the + model is called. If there are multiple calls to + the model, the callback will be executed + multiple times. The provided callbacks are + executed sequentially in the exact order they + are given in the list. If a callback returns an + overridden response, execution stops and any + remaining callbacks are skipped. + after_model_callbacks (MutableSequence[google.cloud.ces_v1beta.types.Callback]): + Optional. The callbacks to execute after the + model is called. If there are multiple calls to + the model, the callback will be executed + multiple times. The provided callbacks are + executed sequentially in the exact order they + are given in the list. If a callback returns an + overridden response, execution stops and any + remaining callbacks are skipped. + before_tool_callbacks (MutableSequence[google.cloud.ces_v1beta.types.Callback]): + Optional. The callbacks to execute before the + tool is invoked. If there are multiple tool + invocations, the callback will be executed + multiple times. The provided callbacks are + executed sequentially in the exact order they + are given in the list. If a callback returns an + overridden response, execution stops and any + remaining callbacks are skipped. + after_tool_callbacks (MutableSequence[google.cloud.ces_v1beta.types.Callback]): + Optional. The callbacks to execute after the + tool is invoked. If there are multiple tool + invocations, the callback will be executed + multiple times. The provided callbacks are + executed sequentially in the exact order they + are given in the list. If a callback returns an + overridden response, execution stops and any + remaining callbacks are skipped. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the agent was + created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the agent was + last updated. + guardrails (MutableSequence[str]): + Optional. List of guardrails for the agent. Format: + ``projects/{project}/locations/{location}/apps/{app}/guardrails/{guardrail}`` + etag (str): + Etag used to ensure the object hasn't changed + during a read-modify-write operation. If the + etag is empty, the update will overwrite any + concurrent changes. + toolsets (MutableSequence[google.cloud.ces_v1beta.types.Agent.AgentToolset]): + Optional. List of toolsets for the agent. + generated_summary (str): + Output only. If the agent is generated by the + LLM assistant, this field contains a descriptive + summary of the generation. + transfer_rules (MutableSequence[google.cloud.ces_v1beta.types.TransferRule]): + Optional. Agent transfer rules. + If multiple rules match, the first one in the + list will be used. + """ + + class LlmAgent(proto.Message): + r"""Default agent type. The agent uses instructions and callbacks + specified in the agent to perform the task using a large + language model. + + """ + + class RemoteDialogflowAgent(proto.Message): + r"""The agent which will transfer execution to a remote `Dialogflow + CX `__ + agent. The Dialogflow agent will process subsequent user queries + until the session ends or flow ends, and the control is transferred + back to the parent CES agent. + + Attributes: + agent (str): + Required. The + `Dialogflow `__ + agent resource name. Format: + ``projects/{project}/locations/{location}/agents/{agent}`` + flow_id (str): + Optional. The flow ID of the flow in the + Dialogflow agent. + environment_id (str): + Optional. The environment ID of the + Dialogflow agent to be used for the agent + execution. If not specified, the draft + environment will be used. + input_variable_mapping (MutableMapping[str, str]): + Optional. The mapping of the app variables + names to the Dialogflow session parameters names + to be sent to the Dialogflow agent as input. + output_variable_mapping (MutableMapping[str, str]): + Optional. The mapping of the Dialogflow + session parameters names to the app variables + names to be sent back to the CES agent after the + Dialogflow agent execution ends. + respect_response_interruption_settings (bool): + Optional. Indicates whether to respect the message-level + interruption settings configured in the Dialogflow agent. + + - If false: all response messages from the Dialogflow agent + follow the app-level barge-in settings. + - If true: only response messages with + ```allow_playback_interruption`` `__ + set to true will be interruptable, all other messages + follow the app-level barge-in settings. + """ + + agent: str = proto.Field( + proto.STRING, + number=1, + ) + flow_id: str = proto.Field( + proto.STRING, + number=2, + ) + environment_id: str = proto.Field( + proto.STRING, + number=3, + ) + input_variable_mapping: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + output_variable_mapping: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + respect_response_interruption_settings: bool = proto.Field( + proto.BOOL, + number=6, + ) + + class AgentToolset(proto.Message): + r"""A toolset with a selection of its tools. + + Attributes: + toolset (str): + Required. The resource name of the toolset. Format: + ``projects/{project}/locations/{location}/apps/{app}/toolsets/{toolset}`` + tool_ids (MutableSequence[str]): + Optional. The tools IDs to filter the + toolset. + """ + + toolset: str = proto.Field( + proto.STRING, + number=1, + ) + tool_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + + llm_agent: LlmAgent = proto.Field( + proto.MESSAGE, + number=26, + oneof="agent_type", + message=LlmAgent, + ) + remote_dialogflow_agent: RemoteDialogflowAgent = proto.Field( + proto.MESSAGE, + number=27, + oneof="agent_type", + message=RemoteDialogflowAgent, + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + model_settings: common.ModelSettings = proto.Field( + proto.MESSAGE, + number=4, + message=common.ModelSettings, + ) + instruction: str = proto.Field( + proto.STRING, + number=6, + ) + tools: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + child_agents: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=8, + ) + before_agent_callbacks: MutableSequence[common.Callback] = proto.RepeatedField( + proto.MESSAGE, + number=18, + message=common.Callback, + ) + after_agent_callbacks: MutableSequence[common.Callback] = proto.RepeatedField( + proto.MESSAGE, + number=19, + message=common.Callback, + ) + before_model_callbacks: MutableSequence[common.Callback] = proto.RepeatedField( + proto.MESSAGE, + number=20, + message=common.Callback, + ) + after_model_callbacks: MutableSequence[common.Callback] = proto.RepeatedField( + proto.MESSAGE, + number=21, + message=common.Callback, + ) + before_tool_callbacks: MutableSequence[common.Callback] = proto.RepeatedField( + proto.MESSAGE, + number=22, + message=common.Callback, + ) + after_tool_callbacks: MutableSequence[common.Callback] = proto.RepeatedField( + proto.MESSAGE, + number=23, + message=common.Callback, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=15, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=16, + message=timestamp_pb2.Timestamp, + ) + guardrails: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=17, + ) + etag: str = proto.Field( + proto.STRING, + number=24, + ) + toolsets: MutableSequence[AgentToolset] = proto.RepeatedField( + proto.MESSAGE, + number=28, + message=AgentToolset, + ) + generated_summary: str = proto.Field( + proto.STRING, + number=29, + ) + transfer_rules: MutableSequence[agent_transfers.TransferRule] = proto.RepeatedField( + proto.MESSAGE, + number=30, + message=agent_transfers.TransferRule, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/agent_service.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/agent_service.py new file mode 100644 index 000000000000..5f33aba432a6 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/agent_service.py @@ -0,0 +1,2353 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.ces_v1beta.types import agent as gcc_agent +from google.cloud.ces_v1beta.types import app as gcc_app +from google.cloud.ces_v1beta.types import app_version as gcc_app_version +from google.cloud.ces_v1beta.types import changelog, conversation, evaluation +from google.cloud.ces_v1beta.types import deployment as gcc_deployment +from google.cloud.ces_v1beta.types import example as gcc_example +from google.cloud.ces_v1beta.types import guardrail as gcc_guardrail +from google.cloud.ces_v1beta.types import tool as gcc_tool +from google.cloud.ces_v1beta.types import toolset as gcc_toolset + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "ListAppsRequest", + "ListAppsResponse", + "GetAppRequest", + "CreateAppRequest", + "UpdateAppRequest", + "DeleteAppRequest", + "ExportAppRequest", + "ExportAppResponse", + "ImportAppRequest", + "ImportAppResponse", + "ListAgentsRequest", + "ListAgentsResponse", + "GetAgentRequest", + "CreateAgentRequest", + "UpdateAgentRequest", + "DeleteAgentRequest", + "OperationMetadata", + "ListExamplesRequest", + "ListExamplesResponse", + "GetExampleRequest", + "CreateExampleRequest", + "UpdateExampleRequest", + "DeleteExampleRequest", + "ListToolsRequest", + "ListToolsResponse", + "GetToolRequest", + "CreateToolRequest", + "UpdateToolRequest", + "DeleteToolRequest", + "ListConversationsRequest", + "ListConversationsResponse", + "GetConversationRequest", + "DeleteConversationRequest", + "BatchDeleteConversationsRequest", + "BatchDeleteConversationsResponse", + "ListGuardrailsRequest", + "ListGuardrailsResponse", + "GetGuardrailRequest", + "CreateGuardrailRequest", + "UpdateGuardrailRequest", + "DeleteGuardrailRequest", + "ListDeploymentsRequest", + "ListDeploymentsResponse", + "GetDeploymentRequest", + "CreateDeploymentRequest", + "UpdateDeploymentRequest", + "DeleteDeploymentRequest", + "ListToolsetsRequest", + "ListToolsetsResponse", + "GetToolsetRequest", + "CreateToolsetRequest", + "UpdateToolsetRequest", + "DeleteToolsetRequest", + "ListAppVersionsRequest", + "ListAppVersionsResponse", + "GetAppVersionRequest", + "DeleteAppVersionRequest", + "CreateAppVersionRequest", + "RestoreAppVersionRequest", + "RestoreAppVersionResponse", + "GenerateAppResourceResponse", + "ListChangelogsRequest", + "ListChangelogsResponse", + "GetChangelogRequest", + }, +) + + +class ListAppsRequest(proto.Message): + r"""Request message for + [AgentService.ListApps][google.cloud.ces.v1beta.AgentService.ListApps]. + + Attributes: + parent (str): + Required. The resource name of the location + to list apps from. + page_size (int): + Optional. Requested page size. Server may + return fewer items than requested. If + unspecified, server will pick an appropriate + default. + page_token (str): + Optional. The + [next_page_token][google.cloud.ces.v1beta.ListAppsResponse.next_page_token] + value returned from a previous list + [AgentService.ListApps][google.cloud.ces.v1beta.AgentService.ListApps] + call. + filter (str): + Optional. Filter to be applied when listing + the apps. See https://google.aip.dev/160 for + more details. + order_by (str): + Optional. Field to sort by. Only "name" and "create_time" is + supported. See https://google.aip.dev/132#ordering for more + details. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListAppsResponse(proto.Message): + r"""Response message for + [AgentService.ListApps][google.cloud.ces.v1beta.AgentService.ListApps]. + + Attributes: + apps (MutableSequence[google.cloud.ces_v1beta.types.App]): + The list of apps. + next_page_token (str): + A token that can be sent as + [ListAppsRequest.page_token][google.cloud.ces.v1beta.ListAppsRequest.page_token] + to retrieve the next page. Absence of this field indicates + there are no subsequent pages. + unreachable (MutableSequence[str]): + Unordered list. Locations that could not be + reached. + """ + + @property + def raw_page(self): + return self + + apps: MutableSequence[gcc_app.App] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcc_app.App, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetAppRequest(proto.Message): + r"""Request message for + [AgentService.GetApp][google.cloud.ces.v1beta.AgentService.GetApp]. + + Attributes: + name (str): + Required. The resource name of the app to + retrieve. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateAppRequest(proto.Message): + r"""Request message for + [AgentService.CreateApp][google.cloud.ces.v1beta.AgentService.CreateApp]. + + Attributes: + parent (str): + Required. The resource name of the location + to create an app in. + app_id (str): + Optional. The ID to use for the app, which + will become the final component of the app's + resource name. If not provided, a unique ID will + be automatically assigned for the app. + app (google.cloud.ces_v1beta.types.App): + Required. The app to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + app_id: str = proto.Field( + proto.STRING, + number=2, + ) + app: gcc_app.App = proto.Field( + proto.MESSAGE, + number=3, + message=gcc_app.App, + ) + + +class UpdateAppRequest(proto.Message): + r"""Request message for + [AgentService.UpdateApp][google.cloud.ces.v1beta.AgentService.UpdateApp]. + + Attributes: + app (google.cloud.ces_v1beta.types.App): + Required. The app to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to control which + fields get updated. If the mask is not present, + all fields will be updated. + """ + + app: gcc_app.App = proto.Field( + proto.MESSAGE, + number=1, + message=gcc_app.App, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteAppRequest(proto.Message): + r"""Request message for + [AgentService.DeleteApp][google.cloud.ces.v1beta.AgentService.DeleteApp]. + + Attributes: + name (str): + Required. The resource name of the app to + delete. + etag (str): + Optional. The current etag of the app. If an + etag is not provided, the deletion will + overwrite any concurrent changes. If an etag is + provided and does not match the current etag of + the app, deletion will be blocked and an ABORTED + error will be returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + etag: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ExportAppRequest(proto.Message): + r"""Request message for + [AgentService.ExportApp][google.cloud.ces.v1beta.AgentService.ExportApp]. + + Attributes: + name (str): + Required. The resource name of the app to + export. + export_format (google.cloud.ces_v1beta.types.ExportAppRequest.ExportFormat): + Required. The format to export the app in. + gcs_uri (str): + Optional. The `Google Cloud + Storage `__ URI to + which to export the app. The format of this URI must be + ``gs:///``. The exported app + archive will be written directly to the specified GCS + object. + """ + + class ExportFormat(proto.Enum): + r"""Export format for the app. + + Values: + EXPORT_FORMAT_UNSPECIFIED (0): + The export format is unspecified. + JSON (1): + The export format is JSON. + YAML (2): + The export format is YAML. + """ + + EXPORT_FORMAT_UNSPECIFIED = 0 + JSON = 1 + YAML = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + export_format: ExportFormat = proto.Field( + proto.ENUM, + number=2, + enum=ExportFormat, + ) + gcs_uri: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ExportAppResponse(proto.Message): + r"""Response message for + [AgentService.ExportApp][google.cloud.ces.v1beta.AgentService.ExportApp]. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + app_content (bytes): + App folder compressed as a zip file. + + This field is a member of `oneof`_ ``app``. + app_uri (str): + The `Google Cloud + Storage `__ URI to + which the app was exported. + + This field is a member of `oneof`_ ``app``. + """ + + app_content: bytes = proto.Field( + proto.BYTES, + number=1, + oneof="app", + ) + app_uri: str = proto.Field( + proto.STRING, + number=2, + oneof="app", + ) + + +class ImportAppRequest(proto.Message): + r"""Request message for + [AgentService.ImportApp][google.cloud.ces.v1beta.AgentService.ImportApp]. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_uri (str): + The `Google Cloud + Storage `__ URI from + which to import app. The format of this URI must be + ``gs:///``. + + This field is a member of `oneof`_ ``app``. + app_content (bytes): + Raw bytes representing the compressed zip + file with the app folder structure. + + This field is a member of `oneof`_ ``app``. + parent (str): + Required. The parent resource name with the + location of the app to import. + display_name (str): + Optional. The display name of the app to import. + + - If the app is created on import, and the display name is + specified, the imported app will use this display name. If + a conflict is detected with an existing app, a timestamp + will be appended to the display name to make it unique. + - If the app is a reimport, this field should not be set. + Providing a display name during reimport will result in an + INVALID_ARGUMENT error. + app_id (str): + Optional. The ID to use for the imported app. + + - If not specified, a unique ID will be automatically + assigned for the app. + - Otherwise, the imported app will use this ID as the final + component of its resource name. If an app with the same ID + already exists at the specified location in the project, + the content of the existing app will be replaced. + import_options (google.cloud.ces_v1beta.types.ImportAppRequest.ImportOptions): + Optional. Options governing the import + process for the app. + ignore_app_lock (bool): + Optional. Flag for overriding the app lock + during import. If set to true, the import + process will ignore the app lock. + """ + + class ImportOptions(proto.Message): + r"""Configuration options for the app import process. + These options control how the import behaves, particularly when + conflicts arise with existing app data. + + Attributes: + conflict_resolution_strategy (google.cloud.ces_v1beta.types.ImportAppRequest.ImportOptions.ConflictResolutionStrategy): + Optional. The strategy to use when resolving + conflicts during import. + """ + + class ConflictResolutionStrategy(proto.Enum): + r"""Defines the strategy for handling conflicts when an app with + the same ID already exists, or when imported resources (like + Agents, Tools, etc.) have the same display names as existing + resources within that app. + + Values: + CONFLICT_RESOLUTION_STRATEGY_UNSPECIFIED (0): + The conflict resolution strategy is + unspecified. + REPLACE (1): + Replace existing data with imported data. If an app with the + same ``app_id`` already exists, its content will be updated + based on the imported app. + + - Resources (App, Agents, Tools, Examples, Guardrails, + Toolsets) in the imported app that have the same display + name as existing resources will overwrite the existing + ones. + - Imported resources with new display names will be created. + - Existing resources that do not have a matching display + name in the imported app will remain untouched. + OVERWRITE (2): + Overwrite existing data with imported data. If an app with + the same ``app_id`` already exists, its content will be + overwritten with the imported app. + + - Existing resources (Agents, Tools, Examples, Guardrails, + Toolsets) in the app will be deleted. + - Imported resources will be created as new resources. + """ + + CONFLICT_RESOLUTION_STRATEGY_UNSPECIFIED = 0 + REPLACE = 1 + OVERWRITE = 2 + + conflict_resolution_strategy: "ImportAppRequest.ImportOptions.ConflictResolutionStrategy" = proto.Field( + proto.ENUM, + number=1, + enum="ImportAppRequest.ImportOptions.ConflictResolutionStrategy", + ) + + gcs_uri: str = proto.Field( + proto.STRING, + number=4, + oneof="app", + ) + app_content: bytes = proto.Field( + proto.BYTES, + number=5, + oneof="app", + ) + parent: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + app_id: str = proto.Field( + proto.STRING, + number=3, + ) + import_options: ImportOptions = proto.Field( + proto.MESSAGE, + number=6, + message=ImportOptions, + ) + ignore_app_lock: bool = proto.Field( + proto.BOOL, + number=7, + ) + + +class ImportAppResponse(proto.Message): + r"""Response message for + [AgentService.ImportApp][google.cloud.ces.v1beta.AgentService.ImportApp]. + + Attributes: + name (str): + The resource name of the app that was + imported. + warnings (MutableSequence[str]): + Warning messages generated during the import + process. If errors occur for specific resources, + they will not be included in the imported app + and the error will be mentioned here. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + warnings: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class ListAgentsRequest(proto.Message): + r"""Request message for + [AgentService.ListAgents][google.cloud.ces.v1beta.AgentService.ListAgents]. + + Attributes: + parent (str): + Required. The resource name of the app to + list agents from. + page_size (int): + Optional. Requested page size. Server may + return fewer items than requested. If + unspecified, server will pick an appropriate + default. + page_token (str): + Optional. The + [next_page_token][google.cloud.ces.v1beta.ListAgentsResponse.next_page_token] + value returned from a previous list + [AgentService.ListAgents][google.cloud.ces.v1beta.AgentService.ListAgents] + call. + filter (str): + Optional. Filter to be applied when listing + the agents. See https://google.aip.dev/160 for + more details. + order_by (str): + Optional. Field to sort by. Only "name" and "create_time" is + supported. See https://google.aip.dev/132#ordering for more + details. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListAgentsResponse(proto.Message): + r"""Response message for + [AgentService.ListAgents][google.cloud.ces.v1beta.AgentService.ListAgents]. + + Attributes: + agents (MutableSequence[google.cloud.ces_v1beta.types.Agent]): + The list of agents. + next_page_token (str): + A token that can be sent as + [ListAgentsRequest.page_token][google.cloud.ces.v1beta.ListAgentsRequest.page_token] + to retrieve the next page. Absence of this field indicates + there are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + agents: MutableSequence[gcc_agent.Agent] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcc_agent.Agent, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetAgentRequest(proto.Message): + r"""Request message for + [AgentService.GetAgent][google.cloud.ces.v1beta.AgentService.GetAgent]. + + Attributes: + name (str): + Required. The resource name of the agent to + retrieve. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateAgentRequest(proto.Message): + r"""Request message for + [AgentService.CreateAgent][google.cloud.ces.v1beta.AgentService.CreateAgent]. + + Attributes: + parent (str): + Required. The resource name of the app to + create an agent in. + agent_id (str): + Optional. The ID to use for the agent, which + will become the final component of the agent's + resource name. If not provided, a unique ID will + be automatically assigned for the agent. + agent (google.cloud.ces_v1beta.types.Agent): + Required. The agent to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + agent_id: str = proto.Field( + proto.STRING, + number=2, + ) + agent: gcc_agent.Agent = proto.Field( + proto.MESSAGE, + number=3, + message=gcc_agent.Agent, + ) + + +class UpdateAgentRequest(proto.Message): + r"""Request message for + [AgentService.UpdateAgent][google.cloud.ces.v1beta.AgentService.UpdateAgent]. + + Attributes: + agent (google.cloud.ces_v1beta.types.Agent): + Required. The agent to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to control which + fields get updated. If the mask is not present, + all fields will be updated. + """ + + agent: gcc_agent.Agent = proto.Field( + proto.MESSAGE, + number=1, + message=gcc_agent.Agent, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteAgentRequest(proto.Message): + r"""Request message for + [AgentService.DeleteAgent][google.cloud.ces.v1beta.AgentService.DeleteAgent]. + + Attributes: + name (str): + Required. The resource name of the agent to + delete. + force (bool): + Optional. Indicates whether to forcefully delete the agent, + even if it is still referenced by other app/agents/examples. + + - If ``force = false``, the deletion fails if other + agents/examples reference it. + - If ``force = true``, delete the agent and remove it from + all referencing apps/agents/examples. + etag (str): + Optional. The current etag of the agent. If + an etag is not provided, the deletion will + overwrite any concurrent changes. If an etag is + provided and does not match the current etag of + the agent, deletion will be blocked and an + ABORTED error will be returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + force: bool = proto.Field( + proto.BOOL, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + + +class OperationMetadata(proto.Message): + r"""Represents the metadata of the long-running operation. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation was + created. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation finished + running. + status_message (str): + Output only. Human-readable status of the + operation, if any. + requested_cancellation (bool): + Output only. Identifies whether the user has requested + cancellation of the operation. Operations that have been + cancelled successfully have + [google.longrunning.Operation.error][google.longrunning.Operation.error] + value with a + [google.rpc.Status.code][google.rpc.Status.code] of ``1``, + corresponding to ``Code.CANCELLED``. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + status_message: str = proto.Field( + proto.STRING, + number=3, + ) + requested_cancellation: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class ListExamplesRequest(proto.Message): + r"""Request message for + [AgentService.ListExamples][google.cloud.ces.v1beta.AgentService.ListExamples]. + + Attributes: + parent (str): + Required. The resource name of the app to + list examples from. + page_size (int): + Optional. Requested page size. Server may + return fewer items than requested. If + unspecified, server will pick an appropriate + default. + page_token (str): + Optional. The + [next_page_token][google.cloud.ces.v1beta.ListExamplesResponse.next_page_token] + value returned from a previous list + [AgentService.ListExamples][google.cloud.ces.v1beta.AgentService.ListExamples] + call. + filter (str): + Optional. Filter to be applied when listing + the examples. See https://google.aip.dev/160 for + more details. + order_by (str): + Optional. Field to sort by. Only "name" and "create_time" is + supported. See https://google.aip.dev/132#ordering for more + details. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListExamplesResponse(proto.Message): + r"""Response message for + [AgentService.ListExamples][google.cloud.ces.v1beta.AgentService.ListExamples]. + + Attributes: + examples (MutableSequence[google.cloud.ces_v1beta.types.Example]): + The list of examples. + next_page_token (str): + A token that can be sent as + [ListExamplesRequest.page_token][google.cloud.ces.v1beta.ListExamplesRequest.page_token] + to retrieve the next page. Absence of this field indicates + there are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + examples: MutableSequence[gcc_example.Example] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcc_example.Example, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetExampleRequest(proto.Message): + r"""Request message for + [AgentService.GetExample][google.cloud.ces.v1beta.AgentService.GetExample]. + + Attributes: + name (str): + Required. The resource name of the example to + retrieve. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateExampleRequest(proto.Message): + r"""Request message for + [AgentService.CreateExample][google.cloud.ces.v1beta.AgentService.CreateExample]. + + Attributes: + parent (str): + Required. The resource name of the app to + create an example in. + example_id (str): + Optional. The ID to use for the example, + which will become the final component of the + example's resource name. If not provided, a + unique ID will be automatically assigned for the + example. + example (google.cloud.ces_v1beta.types.Example): + Required. The example to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + example_id: str = proto.Field( + proto.STRING, + number=2, + ) + example: gcc_example.Example = proto.Field( + proto.MESSAGE, + number=3, + message=gcc_example.Example, + ) + + +class UpdateExampleRequest(proto.Message): + r"""Request message for + [AgentService.UpdateExample][google.cloud.ces.v1beta.AgentService.UpdateExample]. + + Attributes: + example (google.cloud.ces_v1beta.types.Example): + Required. The example to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to control which + fields get updated. If the mask is not present, + all fields will be updated. + """ + + example: gcc_example.Example = proto.Field( + proto.MESSAGE, + number=1, + message=gcc_example.Example, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteExampleRequest(proto.Message): + r"""Request message for + [AgentService.DeleteExample][google.cloud.ces.v1beta.AgentService.DeleteExample]. + + Attributes: + name (str): + Required. The resource name of the example to + delete. + etag (str): + Optional. The current etag of the example. If + an etag is not provided, the deletion will + overwrite any concurrent changes. If an etag is + provided and does not match the current etag of + the example, deletion will be blocked and an + ABORTED error will be returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + etag: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListToolsRequest(proto.Message): + r"""Request message for + [AgentService.ListTools][google.cloud.ces.v1beta.AgentService.ListTools]. + + Attributes: + parent (str): + Required. The resource name of the app to + list tools from. + page_size (int): + Optional. Requested page size. Server may + return fewer items than requested. If + unspecified, server will pick an appropriate + default. + page_token (str): + Optional. The + [next_page_token][google.cloud.ces.v1beta.ListToolsResponse.next_page_token] + value returned from a previous list + [AgentService.ListTools][google.cloud.ces.v1beta.AgentService.ListTools] + call. + filter (str): + Optional. Filter to be applied when listing the tools. Use + "include_system_tools=true" to include system tools in the + response. See https://google.aip.dev/160 for more details. + order_by (str): + Optional. Field to sort by. Only "name" and "create_time" is + supported. See https://google.aip.dev/132#ordering for more + details. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListToolsResponse(proto.Message): + r"""Response message for + [AgentService.ListTools][google.cloud.ces.v1beta.AgentService.ListTools]. + + Attributes: + tools (MutableSequence[google.cloud.ces_v1beta.types.Tool]): + The list of tools. + next_page_token (str): + A token that can be sent as + [ListToolsRequest.page_token][google.cloud.ces.v1beta.ListToolsRequest.page_token] + to retrieve the next page. Absence of this field indicates + there are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + tools: MutableSequence[gcc_tool.Tool] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcc_tool.Tool, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetToolRequest(proto.Message): + r"""Request message for + [AgentService.GetTool][google.cloud.ces.v1beta.AgentService.GetTool]. + + Attributes: + name (str): + Required. The resource name of the tool to + retrieve. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateToolRequest(proto.Message): + r"""Request message for + [AgentService.CreateTool][google.cloud.ces.v1beta.AgentService.CreateTool]. + + Attributes: + parent (str): + Required. The resource name of the app to + create a tool in. + tool_id (str): + Optional. The ID to use for the tool, which + will become the final component of the tool's + resource name. If not provided, a unique ID will + be automatically assigned for the tool. + tool (google.cloud.ces_v1beta.types.Tool): + Required. The tool to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + tool_id: str = proto.Field( + proto.STRING, + number=2, + ) + tool: gcc_tool.Tool = proto.Field( + proto.MESSAGE, + number=3, + message=gcc_tool.Tool, + ) + + +class UpdateToolRequest(proto.Message): + r"""Request message for + [AgentService.UpdateTool][google.cloud.ces.v1beta.AgentService.UpdateTool]. + + Attributes: + tool (google.cloud.ces_v1beta.types.Tool): + Required. The tool to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to control which + fields get updated. If the mask is not present, + all fields will be updated. + """ + + tool: gcc_tool.Tool = proto.Field( + proto.MESSAGE, + number=1, + message=gcc_tool.Tool, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteToolRequest(proto.Message): + r"""Request message for + [AgentService.DeleteTool][google.cloud.ces.v1beta.AgentService.DeleteTool]. + + Attributes: + name (str): + Required. The resource name of the tool to + delete. + force (bool): + Optional. Indicates whether to forcefully delete the tool, + even if it is still referenced by agents/examples. + + - If ``force = false``, the deletion will fail if any agents + still reference the tool. + - If ``force = true``, all existing references from agents + will be removed and the tool will be deleted. + etag (str): + Optional. The current etag of the tool. If an + etag is not provided, the deletion will + overwrite any concurrent changes. If an etag is + provided and does not match the current etag of + the tool, deletion will be blocked and an + ABORTED error will be returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + force: bool = proto.Field( + proto.BOOL, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListConversationsRequest(proto.Message): + r"""Request message for + [AgentService.ListConversations][google.cloud.ces.v1beta.AgentService.ListConversations]. + + Attributes: + parent (str): + Required. The resource name of the app to + list conversations from. + page_size (int): + Optional. Requested page size. Server may + return fewer items than requested. If + unspecified, server will pick an appropriate + default. + page_token (str): + Optional. The + [next_page_token][google.cloud.ces.v1beta.ListConversationsResponse.next_page_token] + value returned from a previous list + [AgentService.ListConversations][google.cloud.ces.v1beta.AgentService.ListConversations] + call. + filter (str): + Optional. Filter to be applied when listing + the conversations. See + https://google.aip.dev/160 for more details. + source (google.cloud.ces_v1beta.types.Conversation.Source): + Optional. Indicate the source of the conversation. If not + set, Source.Live will be applied by default. Will be + deprecated in favor of ``sources`` field. + sources (MutableSequence[google.cloud.ces_v1beta.types.Conversation.Source]): + Optional. Indicate the sources of the + conversations. If not set, all available sources + will be applied by default. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + source: conversation.Conversation.Source = proto.Field( + proto.ENUM, + number=5, + enum=conversation.Conversation.Source, + ) + sources: MutableSequence[conversation.Conversation.Source] = proto.RepeatedField( + proto.ENUM, + number=6, + enum=conversation.Conversation.Source, + ) + + +class ListConversationsResponse(proto.Message): + r"""Response message for + [AgentService.ListConversations][google.cloud.ces.v1beta.AgentService.ListConversations]. + + Attributes: + conversations (MutableSequence[google.cloud.ces_v1beta.types.Conversation]): + The list of conversations. + next_page_token (str): + A token that can be sent as + [ListConversationsRequest.page_token][google.cloud.ces.v1beta.ListConversationsRequest.page_token] + to retrieve the next page. Absence of this field indicates + there are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + conversations: MutableSequence[conversation.Conversation] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=conversation.Conversation, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetConversationRequest(proto.Message): + r"""Request message for + [AgentService.GetConversation][google.cloud.ces.v1beta.AgentService.GetConversation]. + + Attributes: + name (str): + Required. The resource name of the + conversation to retrieve. + source (google.cloud.ces_v1beta.types.Conversation.Source): + Optional. Indicate the source of the + conversation. If not set, all source will be + searched. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + source: conversation.Conversation.Source = proto.Field( + proto.ENUM, + number=2, + enum=conversation.Conversation.Source, + ) + + +class DeleteConversationRequest(proto.Message): + r"""Request message for + [AgentService.DeleteConversation][google.cloud.ces.v1beta.AgentService.DeleteConversation]. + + Attributes: + name (str): + Required. The resource name of the + conversation to delete. + source (google.cloud.ces_v1beta.types.Conversation.Source): + Optional. Indicate the source of the + conversation. If not set, Source.Live will be + applied by default. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + source: conversation.Conversation.Source = proto.Field( + proto.ENUM, + number=2, + enum=conversation.Conversation.Source, + ) + + +class BatchDeleteConversationsRequest(proto.Message): + r"""Request message for + [AgentService.BatchDeleteConversations][google.cloud.ces.v1beta.AgentService.BatchDeleteConversations]. + + Attributes: + parent (str): + Required. The resource name of the app to delete + conversations from. Format: + ``projects/{project}/locations/{location}/apps/{app}`` + conversations (MutableSequence[str]): + Required. The resource names of the + conversations to delete. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + conversations: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class BatchDeleteConversationsResponse(proto.Message): + r"""Response message for + [AgentService.BatchDeleteConversations][google.cloud.ces.v1beta.AgentService.BatchDeleteConversations]. + + Attributes: + deleted_conversations (MutableSequence[str]): + The list of conversations that were + successfully deleted. + failed_conversations (MutableSequence[str]): + The list of conversations that failed to be + deleted. + error_messages (MutableSequence[str]): + Optional. A list of error messages associated + with conversations that failed to be deleted. + """ + + deleted_conversations: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + failed_conversations: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + error_messages: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class ListGuardrailsRequest(proto.Message): + r"""Request message for + [AgentService.ListGuardrails][google.cloud.ces.v1beta.AgentService.ListGuardrails]. + + Attributes: + parent (str): + Required. The resource name of the app to + list guardrails from. + page_size (int): + Optional. Requested page size. Server may + return fewer items than requested. If + unspecified, server will pick an appropriate + default. + page_token (str): + Optional. The + [next_page_token][google.cloud.ces.v1beta.ListGuardrailsResponse.next_page_token] + value returned from a previous list + [AgentService.ListGuardrails][google.cloud.ces.v1beta.AgentService.ListGuardrails] + call. + filter (str): + Optional. Filter to be applied when listing + the guardrails. See https://google.aip.dev/160 + for more details. + order_by (str): + Optional. Field to sort by. Only "name" and "create_time" is + supported. See https://google.aip.dev/132#ordering for more + details. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListGuardrailsResponse(proto.Message): + r"""Response message for + [AgentService.ListGuardrails][google.cloud.ces.v1beta.AgentService.ListGuardrails]. + + Attributes: + guardrails (MutableSequence[google.cloud.ces_v1beta.types.Guardrail]): + The list of guardrails. + next_page_token (str): + A token that can be sent as + [ListGuardrailsRequest.page_token][google.cloud.ces.v1beta.ListGuardrailsRequest.page_token] + to retrieve the next page. Absence of this field indicates + there are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + guardrails: MutableSequence[gcc_guardrail.Guardrail] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcc_guardrail.Guardrail, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetGuardrailRequest(proto.Message): + r"""Request message for + [AgentService.GetGuardrail][google.cloud.ces.v1beta.AgentService.GetGuardrail]. + + Attributes: + name (str): + Required. The resource name of the guardrail + to retrieve. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateGuardrailRequest(proto.Message): + r"""Request message for + [AgentService.CreateGuardrail][google.cloud.ces.v1beta.AgentService.CreateGuardrail]. + + Attributes: + parent (str): + Required. The resource name of the app to + create a guardrail in. + guardrail_id (str): + Optional. The ID to use for the guardrail, + which will become the final component of the + guardrail's resource name. If not provided, a + unique ID will be automatically assigned for the + guardrail. + guardrail (google.cloud.ces_v1beta.types.Guardrail): + Required. The guardrail to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + guardrail_id: str = proto.Field( + proto.STRING, + number=2, + ) + guardrail: gcc_guardrail.Guardrail = proto.Field( + proto.MESSAGE, + number=3, + message=gcc_guardrail.Guardrail, + ) + + +class UpdateGuardrailRequest(proto.Message): + r"""Request message for + [AgentService.UpdateGuardrail][google.cloud.ces.v1beta.AgentService.UpdateGuardrail]. + + Attributes: + guardrail (google.cloud.ces_v1beta.types.Guardrail): + Required. The guardrail to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to control which + fields get updated. If the mask is not present, + all fields will be updated. + """ + + guardrail: gcc_guardrail.Guardrail = proto.Field( + proto.MESSAGE, + number=1, + message=gcc_guardrail.Guardrail, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteGuardrailRequest(proto.Message): + r"""Request message for + [AgentService.DeleteGuardrail][google.cloud.ces.v1beta.AgentService.DeleteGuardrail]. + + Attributes: + name (str): + Required. The resource name of the guardrail + to delete. + force (bool): + Optional. Indicates whether to forcefully delete the + guardrail, even if it is still referenced by app/agents. + + - If ``force = false``, the deletion fails if any + apps/agents still reference the guardrail. + - If ``force = true``, all existing references from + apps/agents will be removed and the guardrail will be + deleted. + etag (str): + Optional. The current etag of the guardrail. + If an etag is not provided, the deletion will + overwrite any concurrent changes. If an etag is + provided and does not match the current etag of + the guardrail, deletion will be blocked and an + ABORTED error will be returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + force: bool = proto.Field( + proto.BOOL, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListDeploymentsRequest(proto.Message): + r"""Request message for + [AgentService.ListDeployments][google.cloud.ces.v1beta.AgentService.ListDeployments]. + + Attributes: + parent (str): + Required. The parent app. Format: + ``projects/{project}/locations/{location}/apps/{app}`` + page_size (int): + Optional. The maximum number of deployments + to return. The service may return fewer than + this value. If unspecified, at most 50 + deployments will be returned. The maximum value + is 1000; values above 1000 will be coerced to + 1000. + page_token (str): + Optional. A page token, received from a previous + ``ListDeployments`` call. Provide this to retrieve the + subsequent page. + + When paginating, all other parameters provided to + ``ListDeployments`` must match the call that provided the + page token. + order_by (str): + Optional. Field to sort by. Only "name" and "create_time" is + supported. See https://google.aip.dev/132#ordering for more + details. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + order_by: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListDeploymentsResponse(proto.Message): + r"""Response message for + [AgentService.ListDeployments][google.cloud.ces.v1beta.AgentService.ListDeployments]. + + Attributes: + deployments (MutableSequence[google.cloud.ces_v1beta.types.Deployment]): + The list of deployments. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + deployments: MutableSequence[gcc_deployment.Deployment] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcc_deployment.Deployment, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetDeploymentRequest(proto.Message): + r"""Request message for + [AgentService.GetDeployment][google.cloud.ces.v1beta.AgentService.GetDeployment]. + + Attributes: + name (str): + Required. The name of the deployment. Format: + ``projects/{project}/locations/{location}/apps/{app}/deployments/{deployment}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateDeploymentRequest(proto.Message): + r"""Request message for + [AgentService.CreateDeployment][google.cloud.ces.v1beta.AgentService.CreateDeployment]. + + Attributes: + parent (str): + Required. The parent app. Format: + ``projects/{project}/locations/{location}/apps/{app}`` + deployment_id (str): + Optional. The ID to use for the deployment, + which will become the final component of the + deployment's resource name. If not provided, a + unique ID will be automatically assigned for the + deployment. + deployment (google.cloud.ces_v1beta.types.Deployment): + Required. The deployment to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + deployment_id: str = proto.Field( + proto.STRING, + number=3, + ) + deployment: gcc_deployment.Deployment = proto.Field( + proto.MESSAGE, + number=2, + message=gcc_deployment.Deployment, + ) + + +class UpdateDeploymentRequest(proto.Message): + r"""Request message for + [AgentService.UpdateDeployment][google.cloud.ces.v1beta.AgentService.UpdateDeployment]. + + Attributes: + deployment (google.cloud.ces_v1beta.types.Deployment): + Required. The deployment to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to update. + """ + + deployment: gcc_deployment.Deployment = proto.Field( + proto.MESSAGE, + number=1, + message=gcc_deployment.Deployment, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteDeploymentRequest(proto.Message): + r"""Request message for + [AgentService.DeleteDeployment][google.cloud.ces.v1beta.AgentService.DeleteDeployment]. + + Attributes: + name (str): + Required. The name of the deployment to delete. Format: + ``projects/{project}/locations/{location}/apps/{app}/deployments/{deployment}`` + etag (str): + Optional. The etag of the deployment. + If an etag is provided and does not match the + current etag of the deployment, deletion will be + blocked and an ABORTED error will be returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + etag: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListToolsetsRequest(proto.Message): + r"""Request message for + [AgentService.ListToolsets][google.cloud.ces.v1beta.AgentService.ListToolsets]. + + Attributes: + parent (str): + Required. The resource name of the app to + list toolsets from. + page_size (int): + Optional. Requested page size. Server may + return fewer items than requested. If + unspecified, server will pick an appropriate + default. + page_token (str): + Optional. The + [next_page_token][google.cloud.ces.v1beta.ListToolsetsResponse.next_page_token] + value returned from a previous list + [AgentService.ListToolsets][google.cloud.ces.v1beta.AgentService.ListToolsets] + call. + filter (str): + Optional. Filter to be applied when listing + the toolsets. See https://google.aip.dev/160 for + more details. + order_by (str): + Optional. Field to sort by. Only "name" and "create_time" is + supported. See https://google.aip.dev/132#ordering for more + details. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListToolsetsResponse(proto.Message): + r"""Response message for + [AgentService.ListToolsets][google.cloud.ces.v1beta.AgentService.ListToolsets]. + + Attributes: + toolsets (MutableSequence[google.cloud.ces_v1beta.types.Toolset]): + The list of toolsets. + next_page_token (str): + A token that can be sent as + [ListToolsetsRequest.page_token][google.cloud.ces.v1beta.ListToolsetsRequest.page_token] + to retrieve the next page. Absence of this field indicates + there are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + toolsets: MutableSequence[gcc_toolset.Toolset] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcc_toolset.Toolset, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetToolsetRequest(proto.Message): + r"""Request message for + [AgentService.GetToolset][google.cloud.ces.v1beta.AgentService.GetToolset]. + + Attributes: + name (str): + Required. The resource name of the toolset to + retrieve. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateToolsetRequest(proto.Message): + r"""Request message for + [AgentService.CreateToolset][google.cloud.ces.v1beta.AgentService.CreateToolset]. + + Attributes: + parent (str): + Required. The resource name of the app to + create a toolset in. + toolset_id (str): + Optional. The ID to use for the toolset, + which will become the final component of the + toolset's resource name. If not provided, a + unique ID will be automatically assigned for the + toolset. + toolset (google.cloud.ces_v1beta.types.Toolset): + Required. The toolset to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + toolset_id: str = proto.Field( + proto.STRING, + number=2, + ) + toolset: gcc_toolset.Toolset = proto.Field( + proto.MESSAGE, + number=3, + message=gcc_toolset.Toolset, + ) + + +class UpdateToolsetRequest(proto.Message): + r"""Request message for + [AgentService.UpdateToolset][google.cloud.ces.v1beta.AgentService.UpdateToolset]. + + Attributes: + toolset (google.cloud.ces_v1beta.types.Toolset): + Required. The toolset to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to control which + fields get updated. If the mask is not present, + all fields will be updated. + """ + + toolset: gcc_toolset.Toolset = proto.Field( + proto.MESSAGE, + number=1, + message=gcc_toolset.Toolset, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteToolsetRequest(proto.Message): + r"""Request message for + [AgentService.DeleteToolset][google.cloud.ces.v1beta.AgentService.DeleteToolset]. + + Attributes: + name (str): + Required. The resource name of the toolset to + delete. + force (bool): + Optional. Indicates whether to forcefully delete the + toolset, even if it is still referenced by app/agents. + + - If ``force = false``, the deletion fails if any agents + still reference the toolset. + - If ``force = true``, all existing references from agents + will be removed and the toolset will be deleted. + etag (str): + Optional. The current etag of the toolset. If + an etag is not provided, the deletion will + overwrite any concurrent changes. If an etag is + provided and does not match the current etag of + the toolset, deletion will be blocked and an + ABORTED error will be returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + force: bool = proto.Field( + proto.BOOL, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListAppVersionsRequest(proto.Message): + r"""Request message for + [AgentService.ListAppVersions][google.cloud.ces.v1beta.AgentService.ListAppVersions]. + + Attributes: + parent (str): + Required. The resource name of the app to + list app versions from. + page_size (int): + Optional. Requested page size. Server may + return fewer items than requested. If + unspecified, server will pick an appropriate + default. + page_token (str): + Optional. The + [next_page_token][google.cloud.ces.v1beta.ListAppVersionsResponse.next_page_token] + value returned from a previous list + [AgentService.ListAppVersions][google.cloud.ces.v1beta.AgentService.ListAppVersions] + call. + filter (str): + Optional. Filter to be applied when listing + the app versions. See https://google.aip.dev/160 + for more details. + order_by (str): + Optional. Field to sort by. Only "name" and "create_time" is + supported. See https://google.aip.dev/132#ordering for more + details. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListAppVersionsResponse(proto.Message): + r"""Response message for + [AgentService.ListAppVersions][google.cloud.ces.v1beta.AgentService.ListAppVersions]. + + Attributes: + app_versions (MutableSequence[google.cloud.ces_v1beta.types.AppVersion]): + The list of app versions. + next_page_token (str): + A token that can be sent as + [ListAppVersionsRequest.page_token][google.cloud.ces.v1beta.ListAppVersionsRequest.page_token] + to retrieve the next page. Absence of this field indicates + there are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + app_versions: MutableSequence[gcc_app_version.AppVersion] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcc_app_version.AppVersion, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetAppVersionRequest(proto.Message): + r"""Request message for + [AgentService.GetAppVersion][google.cloud.ces.v1beta.AgentService.GetAppVersion]. + + Attributes: + name (str): + Required. The resource name of the app + version to retrieve. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteAppVersionRequest(proto.Message): + r"""Request message for + [AgentService.DeleteAppVersion][google.cloud.ces.v1beta.AgentService.DeleteAppVersion]. + + Attributes: + name (str): + Required. The resource name of the app + version to delete. + etag (str): + Optional. The current etag of the app + version. If an etag is not provided, the + deletion will overwrite any concurrent changes. + If an etag is provided and does not match the + current etag of the app version, deletion will + be blocked and an ABORTED error will be + returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + etag: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateAppVersionRequest(proto.Message): + r"""Request message for + [AgentService.CreateAppVersion][google.cloud.ces.v1beta.AgentService.CreateAppVersion] + + Attributes: + parent (str): + Required. The resource name of the app to + create an app version in. + app_version_id (str): + Optional. The ID to use for the app version, + which will become the final component of the app + version's resource name. If not provided, a + unique ID will be automatically assigned for the + app version. + app_version (google.cloud.ces_v1beta.types.AppVersion): + Required. The app version to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + app_version_id: str = proto.Field( + proto.STRING, + number=2, + ) + app_version: gcc_app_version.AppVersion = proto.Field( + proto.MESSAGE, + number=3, + message=gcc_app_version.AppVersion, + ) + + +class RestoreAppVersionRequest(proto.Message): + r"""Request message for + [AgentService.RestoreAppVersion][google.cloud.ces.v1beta.AgentService.RestoreAppVersion] + + Attributes: + name (str): + Required. The resource name of the app + version to restore. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class RestoreAppVersionResponse(proto.Message): + r"""Response message for + [AgentService.RestoreAppVersion][google.cloud.ces.v1beta.AgentService.RestoreAppVersion] + + """ + + +class GenerateAppResourceResponse(proto.Message): + r"""Response message for + [AgentService.GenerateAppResource][google.cloud.ces.v1beta.AgentService.GenerateAppResource]. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + agent (google.cloud.ces_v1beta.types.Agent): + Agent generated by the LLM assistant. + + This field is a member of `oneof`_ ``generated_resource``. + toolset (google.cloud.ces_v1beta.types.Toolset): + Toolset generated by the LLM assistant. + Supports Open API toolset schema generation. + + This field is a member of `oneof`_ ``generated_resource``. + app_snapshot (google.cloud.ces_v1beta.types.AppSnapshot): + App snapshot generated by the LLM assistant. + This snapshot contains the app, agents & tools + generated by the LLM assistant. + + This field is a member of `oneof`_ ``generated_resource``. + tools (google.cloud.ces_v1beta.types.GenerateAppResourceResponse.Tools): + The list of tools generated by the LLM + assistant. + + This field is a member of `oneof`_ ``generated_resource``. + evaluations (google.cloud.ces_v1beta.types.GenerateAppResourceResponse.Evaluations): + Evaluations generated by the LLM assistant. + + This field is a member of `oneof`_ ``generated_resource``. + app_resources (google.cloud.ces_v1beta.types.GenerateAppResourceResponse.AppResources): + The app resources generated by the LLM + assistant. + + This field is a member of `oneof`_ ``generated_resource``. + generate_result_info (google.cloud.ces_v1beta.types.GenerateAppResourceResponse.GenerateResultInfo): + Additional information about the generated + result. + """ + + class Evaluations(proto.Message): + r"""The list of evaluations generated by the LLM assistant. + + Attributes: + evaluations (MutableSequence[google.cloud.ces_v1beta.types.Evaluation]): + The list of generated evaluations. + """ + + evaluations: MutableSequence[evaluation.Evaluation] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=evaluation.Evaluation, + ) + + class Tools(proto.Message): + r"""The list of tools generated by the LLM assistant. + + Attributes: + tools (MutableSequence[google.cloud.ces_v1beta.types.Tool]): + The list of tools generated by the LLM + assistant. + """ + + tools: MutableSequence[gcc_tool.Tool] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcc_tool.Tool, + ) + + class AppResources(proto.Message): + r"""The list of app resources generated by the LLM assistant. + + Attributes: + app_snapshot (google.cloud.ces_v1beta.types.AppSnapshot): + The app snapshot generated by the LLM + assistant. This snapshot contains the app, + agents & tools generated by the LLM assistant. + evaluations (MutableSequence[google.cloud.ces_v1beta.types.Evaluation]): + The list of evaluations generated by the LLM + assistant. + """ + + app_snapshot: gcc_app_version.AppSnapshot = proto.Field( + proto.MESSAGE, + number=1, + message=gcc_app_version.AppSnapshot, + ) + evaluations: MutableSequence[evaluation.Evaluation] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=evaluation.Evaluation, + ) + + class GenerateResultInfo(proto.Message): + r"""This provides additional information about the generated + result. + + Attributes: + explanation (str): + An explanation of the changes in the + generated resource. + """ + + explanation: str = proto.Field( + proto.STRING, + number=1, + ) + + agent: gcc_agent.Agent = proto.Field( + proto.MESSAGE, + number=1, + oneof="generated_resource", + message=gcc_agent.Agent, + ) + toolset: gcc_toolset.Toolset = proto.Field( + proto.MESSAGE, + number=3, + oneof="generated_resource", + message=gcc_toolset.Toolset, + ) + app_snapshot: gcc_app_version.AppSnapshot = proto.Field( + proto.MESSAGE, + number=4, + oneof="generated_resource", + message=gcc_app_version.AppSnapshot, + ) + tools: Tools = proto.Field( + proto.MESSAGE, + number=5, + oneof="generated_resource", + message=Tools, + ) + evaluations: Evaluations = proto.Field( + proto.MESSAGE, + number=6, + oneof="generated_resource", + message=Evaluations, + ) + app_resources: AppResources = proto.Field( + proto.MESSAGE, + number=7, + oneof="generated_resource", + message=AppResources, + ) + generate_result_info: GenerateResultInfo = proto.Field( + proto.MESSAGE, + number=2, + message=GenerateResultInfo, + ) + + +class ListChangelogsRequest(proto.Message): + r"""Request message for + [AgentService.ListChangelogs][google.cloud.ces.v1beta.AgentService.ListChangelogs]. + + Attributes: + parent (str): + Required. The resource name of the app to + list changelogs from. + page_size (int): + Optional. Requested page size. Server may + return fewer items than requested. If + unspecified, server will pick an appropriate + default. + page_token (str): + Optional. The + [next_page_token][google.cloud.ces.v1beta.ListChangelogsResponse.next_page_token] + value returned from a previous list + [AgentService.ListChangelogs][google.cloud.ces.v1beta.AgentService.ListChangelogs] + call. + filter (str): + Optional. Filter to be applied when listing the changelogs. + See https://google.aip.dev/160 for more details. + + The filter string can be used to filter by ``action``, + ``resource_type``, ``resource_name``, ``author``, and + ``create_time``. The ``:`` comparator can be used for + case-insensitive partial matching on string fields, while + ``=`` performs an exact case-sensitive match. + + Examples: + + - ``action:update`` (case-insensitive partial match) + - ``action="Create"`` (case-sensitive exact match) + - ``resource_type:agent`` + - ``resource_name:my-agent`` + - ``author:me@example.com`` + - ``create_time > "2025-01-01T00:00:00Z"`` + - ``create_time <= "2025-01-01T00:00:00Z" AND resource_type:tool`` + order_by (str): + Optional. Field to sort by. Only "name" and "create_time" is + supported. See https://google.aip.dev/132#ordering for more + details. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListChangelogsResponse(proto.Message): + r"""Response message for + [AgentService.ListChangelogs][google.cloud.ces.v1beta.AgentService.ListChangelogs]. + + Attributes: + changelogs (MutableSequence[google.cloud.ces_v1beta.types.Changelog]): + The list of changelogs. + next_page_token (str): + A token that can be sent as + [ListChangelogsRequest.page_token][google.cloud.ces.v1beta.ListChangelogsRequest.page_token] + to retrieve the next page. Absence of this field indicates + there are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + changelogs: MutableSequence[changelog.Changelog] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=changelog.Changelog, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetChangelogRequest(proto.Message): + r"""Request message for + [AgentService.GetChangelog][google.cloud.ces.v1beta.AgentService.GetChangelog]. + + Attributes: + name (str): + Required. The resource name of the changelog + to retrieve. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/agent_transfers.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/agent_transfers.py new file mode 100644 index 000000000000..5e1ae662d0ea --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/agent_transfers.py @@ -0,0 +1,187 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "ExpressionCondition", + "PythonCodeCondition", + "TransferRule", + }, +) + + +class ExpressionCondition(proto.Message): + r"""Expression condition based on session state. + + Attributes: + expression (str): + Required. The string representation of + cloud.api.Expression condition. + """ + + expression: str = proto.Field( + proto.STRING, + number=1, + ) + + +class PythonCodeCondition(proto.Message): + r"""Python code block to evaluate the condition. + + Attributes: + python_code (str): + Required. The python code to execute. + """ + + python_code: str = proto.Field( + proto.STRING, + number=1, + ) + + +class TransferRule(proto.Message): + r"""Rule for transferring to a specific agent. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + deterministic_transfer (google.cloud.ces_v1beta.types.TransferRule.DeterministicTransfer): + Optional. A rule that immediately transfers + to the target agent when the condition is met. + + This field is a member of `oneof`_ ``rule_type``. + disable_planner_transfer (google.cloud.ces_v1beta.types.TransferRule.DisablePlannerTransfer): + Optional. Rule that prevents the planner from + transferring to the target agent. + + This field is a member of `oneof`_ ``rule_type``. + child_agent (str): + Required. The resource name of the child agent the rule + applies to. Format: + ``projects/{project}/locations/{location}/apps/{app}/agents/{agent}`` + direction (google.cloud.ces_v1beta.types.TransferRule.Direction): + Required. The direction of the transfer. + """ + + class Direction(proto.Enum): + r"""The direction of the transfer. + + Values: + DIRECTION_UNSPECIFIED (0): + Unspecified direction. + PARENT_TO_CHILD (1): + Transfer from the parent agent to the child + agent. + CHILD_TO_PARENT (2): + Transfer from the child agent to the parent + agent. + """ + + DIRECTION_UNSPECIFIED = 0 + PARENT_TO_CHILD = 1 + CHILD_TO_PARENT = 2 + + class DeterministicTransfer(proto.Message): + r"""Deterministic transfer rule. When the condition evaluates to + true, the transfer occurs. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + expression_condition (google.cloud.ces_v1beta.types.ExpressionCondition): + Optional. A rule that evaluates a session + state condition. If the condition evaluates to + true, the transfer occurs. + + This field is a member of `oneof`_ ``condition_type``. + python_code_condition (google.cloud.ces_v1beta.types.PythonCodeCondition): + Optional. A rule that uses Python code block + to evaluate the conditions. If the condition + evaluates to true, the transfer occurs. + + This field is a member of `oneof`_ ``condition_type``. + """ + + expression_condition: "ExpressionCondition" = proto.Field( + proto.MESSAGE, + number=1, + oneof="condition_type", + message="ExpressionCondition", + ) + python_code_condition: "PythonCodeCondition" = proto.Field( + proto.MESSAGE, + number=2, + oneof="condition_type", + message="PythonCodeCondition", + ) + + class DisablePlannerTransfer(proto.Message): + r"""A rule that prevents the planner from transferring to the + target agent. + + Attributes: + expression_condition (google.cloud.ces_v1beta.types.ExpressionCondition): + Required. If the condition evaluates to true, + planner will not be allowed to transfer to the + target agent. + """ + + expression_condition: "ExpressionCondition" = proto.Field( + proto.MESSAGE, + number=1, + message="ExpressionCondition", + ) + + deterministic_transfer: DeterministicTransfer = proto.Field( + proto.MESSAGE, + number=3, + oneof="rule_type", + message=DeterministicTransfer, + ) + disable_planner_transfer: DisablePlannerTransfer = proto.Field( + proto.MESSAGE, + number=4, + oneof="rule_type", + message=DisablePlannerTransfer, + ) + child_agent: str = proto.Field( + proto.STRING, + number=1, + ) + direction: Direction = proto.Field( + proto.ENUM, + number=2, + enum=Direction, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/app.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/app.py new file mode 100644 index 000000000000..86ec08a93b78 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/app.py @@ -0,0 +1,1328 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.ces_v1beta.types import bigquery_export, common, fakes, golden_run +from google.cloud.ces_v1beta.types import schema as gcc_schema + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "App", + "TimeZoneSettings", + "LanguageSettings", + "AudioProcessingConfig", + "AmbientSoundConfig", + "BargeInConfig", + "SynthesizeSpeechConfig", + "MetricAnalysisSettings", + "LoggingSettings", + "ErrorHandlingSettings", + "EvaluationMetricsThresholds", + "EvaluationSettings", + "ClientCertificateSettings", + "ConversationLoggingSettings", + "CloudLoggingSettings", + "AudioRecordingConfig", + "RedactionConfig", + "DataStoreSettings", + "EvaluationPersona", + }, +) + + +class App(proto.Message): + r"""An app serves as a top-level container for a group of agents, + including the root agent and its sub-agents, along with their + associated configurations. These agents work together to achieve + specific goals within the app's context. + + Attributes: + name (str): + Identifier. The unique identifier of the app. Format: + ``projects/{project}/locations/{location}/apps/{app}`` + display_name (str): + Required. Display name of the app. + description (str): + Optional. Human-readable description of the + app. + pinned (bool): + Optional. Whether the app is pinned in the + app list. + root_agent (str): + Optional. The root agent is the entry point of the app. + Format: + ``projects/{project}/locations/{location}/apps/{app}/agents/{agent}`` + language_settings (google.cloud.ces_v1beta.types.LanguageSettings): + Optional. Language settings of the app. + time_zone_settings (google.cloud.ces_v1beta.types.TimeZoneSettings): + Optional. TimeZone settings of the app. + audio_processing_config (google.cloud.ces_v1beta.types.AudioProcessingConfig): + Optional. Audio processing configuration of + the app. + logging_settings (google.cloud.ces_v1beta.types.LoggingSettings): + Optional. Logging settings of the app. + error_handling_settings (google.cloud.ces_v1beta.types.ErrorHandlingSettings): + Optional. Error handling settings of the app. + model_settings (google.cloud.ces_v1beta.types.ModelSettings): + Optional. The default LLM model settings for + the app. Individual resources (e.g. agents, + guardrails) can override these configurations as + needed. + tool_execution_mode (google.cloud.ces_v1beta.types.App.ToolExecutionMode): + Optional. The tool execution mode for the + app. If not provided, will default to PARALLEL. + evaluation_metrics_thresholds (google.cloud.ces_v1beta.types.EvaluationMetricsThresholds): + Optional. The evaluation thresholds for the + app. + variable_declarations (MutableSequence[google.cloud.ces_v1beta.types.App.VariableDeclaration]): + Optional. The declarations of the variables. + predefined_variable_declarations (MutableSequence[google.cloud.ces_v1beta.types.App.VariableDeclaration]): + Output only. The declarations of predefined + variables for the app. + global_instruction (str): + Optional. Instructions for all the agents in + the app. You can use this instruction to set up + a stable identity or personality across all the + agents. + guardrails (MutableSequence[str]): + Optional. List of guardrails for the app. Format: + ``projects/{project}/locations/{location}/apps/{app}/guardrails/{guardrail}`` + data_store_settings (google.cloud.ces_v1beta.types.DataStoreSettings): + Optional. The data store settings for the + app. + default_channel_profile (google.cloud.ces_v1beta.types.ChannelProfile): + Optional. The default channel profile used by + the app. + metadata (MutableMapping[str, str]): + Optional. Metadata about the app. This field + can be used to store additional information + relevant to the app's details or intended + usages. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the app was + created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the app was last + updated. + etag (str): + Output only. Etag used to ensure the object + hasn't changed during a read-modify-write + operation. If the etag is empty, the update will + overwrite any concurrent changes. + deployment_count (int): + Output only. Number of deployments in the + app. + client_certificate_settings (google.cloud.ces_v1beta.types.ClientCertificateSettings): + Optional. The default client certificate + settings for the app. + locked (bool): + Optional. Indicates whether the app is locked + for changes. If the app is locked, modifications + to the app resources will be rejected. + evaluation_personas (MutableSequence[google.cloud.ces_v1beta.types.EvaluationPersona]): + Optional. The evaluation personas for the + app. This field is used to define the personas + that can be used for evaluation. Maximum of 30 + personas can be defined. + evaluation_settings (google.cloud.ces_v1beta.types.EvaluationSettings): + Optional. The evaluation settings for the + app. + """ + + class ToolExecutionMode(proto.Enum): + r"""Defines the tool execution behavior if there are **multiple** tools + being selected by the agent **at the same time**. + + Values: + TOOL_EXECUTION_MODE_UNSPECIFIED (0): + Unspecified tool execution mode. Default to + PARALLEL. + PARALLEL (1): + If there are multiple tools being selected, they will be + executed in parallel, with the same + `ToolContext `__. + SEQUENTIAL (2): + If there are multiple tools being selected, they will be + executed sequentially. The next tool will only be executed + after the previous tool completes and it can see updated + `ToolContext `__ + from the previous tool. + """ + + TOOL_EXECUTION_MODE_UNSPECIFIED = 0 + PARALLEL = 1 + SEQUENTIAL = 2 + + class VariableDeclaration(proto.Message): + r"""Defines the structure and metadata for a variable. + + Attributes: + name (str): + Required. The name of the variable. The name + must start with a letter or underscore and + contain only letters, numbers, or underscores. + description (str): + Required. The description of the variable. + schema (google.cloud.ces_v1beta.types.Schema): + Required. The schema of the variable. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + schema: gcc_schema.Schema = proto.Field( + proto.MESSAGE, + number=3, + message=gcc_schema.Schema, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + pinned: bool = proto.Field( + proto.BOOL, + number=31, + ) + root_agent: str = proto.Field( + proto.STRING, + number=4, + ) + language_settings: "LanguageSettings" = proto.Field( + proto.MESSAGE, + number=18, + message="LanguageSettings", + ) + time_zone_settings: "TimeZoneSettings" = proto.Field( + proto.MESSAGE, + number=27, + message="TimeZoneSettings", + ) + audio_processing_config: "AudioProcessingConfig" = proto.Field( + proto.MESSAGE, + number=7, + message="AudioProcessingConfig", + ) + logging_settings: "LoggingSettings" = proto.Field( + proto.MESSAGE, + number=8, + message="LoggingSettings", + ) + error_handling_settings: "ErrorHandlingSettings" = proto.Field( + proto.MESSAGE, + number=34, + message="ErrorHandlingSettings", + ) + model_settings: common.ModelSettings = proto.Field( + proto.MESSAGE, + number=13, + message=common.ModelSettings, + ) + tool_execution_mode: ToolExecutionMode = proto.Field( + proto.ENUM, + number=32, + enum=ToolExecutionMode, + ) + evaluation_metrics_thresholds: "EvaluationMetricsThresholds" = proto.Field( + proto.MESSAGE, + number=24, + message="EvaluationMetricsThresholds", + ) + variable_declarations: MutableSequence[VariableDeclaration] = proto.RepeatedField( + proto.MESSAGE, + number=14, + message=VariableDeclaration, + ) + predefined_variable_declarations: MutableSequence[VariableDeclaration] = ( + proto.RepeatedField( + proto.MESSAGE, + number=28, + message=VariableDeclaration, + ) + ) + global_instruction: str = proto.Field( + proto.STRING, + number=17, + ) + guardrails: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=10, + ) + data_store_settings: "DataStoreSettings" = proto.Field( + proto.MESSAGE, + number=15, + message="DataStoreSettings", + ) + default_channel_profile: common.ChannelProfile = proto.Field( + proto.MESSAGE, + number=22, + message=common.ChannelProfile, + ) + metadata: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=11, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + etag: str = proto.Field( + proto.STRING, + number=12, + ) + deployment_count: int = proto.Field( + proto.INT32, + number=23, + ) + client_certificate_settings: "ClientCertificateSettings" = proto.Field( + proto.MESSAGE, + number=25, + message="ClientCertificateSettings", + ) + locked: bool = proto.Field( + proto.BOOL, + number=29, + ) + evaluation_personas: MutableSequence["EvaluationPersona"] = proto.RepeatedField( + proto.MESSAGE, + number=30, + message="EvaluationPersona", + ) + evaluation_settings: "EvaluationSettings" = proto.Field( + proto.MESSAGE, + number=33, + message="EvaluationSettings", + ) + + +class TimeZoneSettings(proto.Message): + r"""TimeZone settings of the app. + + Attributes: + time_zone (str): + Optional. The time zone of the app from the `time zone + database `__, e.g., + America/Los_Angeles, Europe/Paris. + """ + + time_zone: str = proto.Field( + proto.STRING, + number=1, + ) + + +class LanguageSettings(proto.Message): + r"""Language settings of the app. + + Attributes: + default_language_code (str): + Optional. The default language code of the + app. + supported_language_codes (MutableSequence[str]): + Optional. List of languages codes supported by the app, in + addition to the ``default_language_code``. + enable_multilingual_support (bool): + Optional. Enables multilingual support. If + true, agents in the app will use pre-built + instructions to improve handling of multilingual + input. + fallback_action (str): + Optional. The action to perform when an agent receives input + in an unsupported language. + + This can be a predefined action or a custom tool call. Valid + values are: + + - A tool's full resource name, which triggers a specific + tool execution. + - A predefined system action, such as "escalate" or "exit", + which triggers an + [EndSession][google.cloud.ces.v1beta.EndSession] signal + with corresponding + [metadata][google.cloud.ces.v1beta.EndSession.metadata] to + terminate the conversation. + """ + + default_language_code: str = proto.Field( + proto.STRING, + number=1, + ) + supported_language_codes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + enable_multilingual_support: bool = proto.Field( + proto.BOOL, + number=3, + ) + fallback_action: str = proto.Field( + proto.STRING, + number=4, + ) + + +class AudioProcessingConfig(proto.Message): + r"""Configuration for how the input and output audio should be + processed and delivered. + + Attributes: + synthesize_speech_configs (MutableMapping[str, google.cloud.ces_v1beta.types.SynthesizeSpeechConfig]): + Optional. Configuration of how the agent response should be + synthesized, mapping from the language code to + [SynthesizeSpeechConfig][google.cloud.ces.v1beta.SynthesizeSpeechConfig]. + + If the configuration for the specified language code is not + found, the configuration for the root language code will be + used. For example, if the map contains "en-us" and "en", and + the specified language code is "en-gb", then "en" + configuration will be used. + + Note: Language code is case-insensitive. + barge_in_config (google.cloud.ces_v1beta.types.BargeInConfig): + Optional. Configures the agent behavior for + the user barge-in activities. + inactivity_timeout (google.protobuf.duration_pb2.Duration): + Optional. The duration of user inactivity (no + speech or interaction) before the agent prompts + the user for reengagement. If not set, the agent + will not prompt the user for reengagement. + ambient_sound_config (google.cloud.ces_v1beta.types.AmbientSoundConfig): + Optional. Configuration for the ambient sound + to be played with the synthesized agent + response, to enhance the naturalness of the + conversation. + """ + + synthesize_speech_configs: MutableMapping[str, "SynthesizeSpeechConfig"] = ( + proto.MapField( + proto.STRING, + proto.MESSAGE, + number=1, + message="SynthesizeSpeechConfig", + ) + ) + barge_in_config: "BargeInConfig" = proto.Field( + proto.MESSAGE, + number=3, + message="BargeInConfig", + ) + inactivity_timeout: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + ambient_sound_config: "AmbientSoundConfig" = proto.Field( + proto.MESSAGE, + number=5, + message="AmbientSoundConfig", + ) + + +class AmbientSoundConfig(proto.Message): + r"""Configuration for the ambient sound to be played with the + synthesized agent response, to enhance the naturalness of the + conversation. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + prebuilt_ambient_noise (google.cloud.ces_v1beta.types.AmbientSoundConfig.PrebuiltAmbientNoise): + Optional. Deprecated: ``prebuilt_ambient_noise`` is + deprecated in favor of ``prebuilt_ambient_sound``. + + This field is a member of `oneof`_ ``source``. + gcs_uri (str): + Optional. Ambient noise as a mono-channel, 16kHz WAV file + stored in `Cloud + Storage `__. + + Note: Please make sure the CES service agent + ``service-@gcp-sa-ces.iam.gserviceaccount.com`` + has ``storage.objects.get`` permission to the Cloud Storage + object. + + This field is a member of `oneof`_ ``source``. + prebuilt_ambient_sound (str): + Optional. Name of the prebuilt ambient sound. Valid values + are: + + - "coffee_shop" + - "keyboard" + - "keypad" + - "hum" + - "office_1" + - "office_2" + - "office_3" + - "room_1" + - "room_2" + - "room_3" + - "room_4" + - "room_5" + - "air_conditioner". + + This field is a member of `oneof`_ ``source``. + volume_gain_db (float): + Optional. Volume gain (in dB) of the normal native volume + supported by ambient noise, in the range [-96.0, 16.0]. If + unset, or set to a value of 0.0 (dB), will play at normal + native signal amplitude. A value of -6.0 (dB) will play at + approximately half the amplitude of the normal native signal + amplitude. A value of +6.0 (dB) will play at approximately + twice the amplitude of the normal native signal amplitude. + We strongly recommend not to exceed +10 (dB) as there's + usually no effective increase in loudness for any value + greater than that. + """ + + class PrebuiltAmbientNoise(proto.Enum): + r"""Prebuilt ambient noise. + + Values: + PREBUILT_AMBIENT_NOISE_UNSPECIFIED (0): + Not specified. + RETAIL_STORE (1): + Ambient noise of a retail store. + CONVENTION_HALL (2): + Ambient noise of a convention hall. + OUTDOOR (3): + Ambient noise of a street. + """ + + PREBUILT_AMBIENT_NOISE_UNSPECIFIED = 0 + RETAIL_STORE = 1 + CONVENTION_HALL = 2 + OUTDOOR = 3 + + prebuilt_ambient_noise: PrebuiltAmbientNoise = proto.Field( + proto.ENUM, + number=1, + oneof="source", + enum=PrebuiltAmbientNoise, + ) + gcs_uri: str = proto.Field( + proto.STRING, + number=2, + oneof="source", + ) + prebuilt_ambient_sound: str = proto.Field( + proto.STRING, + number=4, + oneof="source", + ) + volume_gain_db: float = proto.Field( + proto.DOUBLE, + number=3, + ) + + +class BargeInConfig(proto.Message): + r"""Configuration for how the user barge-in activities should be + handled. + + Attributes: + disable_barge_in (bool): + Optional. Disables user barge-in while the agent is + speaking. If true, user input during agent response playback + will be ignored. + + Deprecated: ``disable_barge_in`` is deprecated in favor of + [``disable_barge_in_control``][google.cloud.ces.v1beta.ChannelProfile.disable_barge_in_control] + in ChannelProfile. + barge_in_awareness (bool): + Optional. If enabled, the agent will adapt + its next response based on the assumption that + the user hasn't heard the full preceding agent + message. This should not be used in scenarios + where agent responses are displayed visually. + """ + + disable_barge_in: bool = proto.Field( + proto.BOOL, + number=1, + ) + barge_in_awareness: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class SynthesizeSpeechConfig(proto.Message): + r"""Configuration for how the agent response should be + synthesized. + + Attributes: + voice (str): + Optional. The name of the voice. If not set, the service + will choose a voice based on the other parameters such as + language_code. + + For the list of available voices, please refer to `Supported + voices and + languages `__ + from Cloud Text-to-Speech. + speaking_rate (float): + Optional. The speaking rate/speed in the range [0.25, 2.0]. + 1.0 is the normal native speed supported by the specific + voice. 2.0 is twice as fast, and 0.5 is half as fast. Values + outside of the range [0.25, 2.0] will return an error. + """ + + voice: str = proto.Field( + proto.STRING, + number=1, + ) + speaking_rate: float = proto.Field( + proto.DOUBLE, + number=2, + ) + + +class MetricAnalysisSettings(proto.Message): + r"""Settings to describe the conversation data collection + behaviors for LLM analysis metrics pipeline. + + Attributes: + llm_metrics_opted_out (bool): + Optional. Whether to collect conversation + data for llm analysis metrics. If true, + conversation data will not be collected for llm + analysis metrics; otherwise, conversation data + will be collected. + """ + + llm_metrics_opted_out: bool = proto.Field( + proto.BOOL, + number=1, + ) + + +class LoggingSettings(proto.Message): + r"""Settings to describe the logging behaviors for the app. + + Attributes: + redaction_config (google.cloud.ces_v1beta.types.RedactionConfig): + Optional. Configuration for how sensitive + data should be redacted. + audio_recording_config (google.cloud.ces_v1beta.types.AudioRecordingConfig): + Optional. Configuration for how audio + interactions should be recorded. + bigquery_export_settings (google.cloud.ces_v1beta.types.BigQueryExportSettings): + Optional. Settings to describe the BigQuery + export behaviors for the app. The conversation + data will be exported to BigQuery tables if it + is enabled. + cloud_logging_settings (google.cloud.ces_v1beta.types.CloudLoggingSettings): + Optional. Settings to describe the Cloud + Logging behaviors for the app. + conversation_logging_settings (google.cloud.ces_v1beta.types.ConversationLoggingSettings): + Optional. Settings to describe the + conversation logging behaviors for the app. + evaluation_audio_recording_config (google.cloud.ces_v1beta.types.AudioRecordingConfig): + Optional. Configuration for how audio + interactions should be recorded for the + evaluation. By default, audio recording is not + enabled for evaluation sessions. + metric_analysis_settings (google.cloud.ces_v1beta.types.MetricAnalysisSettings): + Optional. Settings to describe the + conversation data collection behaviors for the + LLM analysis pipeline for the app. + """ + + redaction_config: "RedactionConfig" = proto.Field( + proto.MESSAGE, + number=1, + message="RedactionConfig", + ) + audio_recording_config: "AudioRecordingConfig" = proto.Field( + proto.MESSAGE, + number=2, + message="AudioRecordingConfig", + ) + bigquery_export_settings: bigquery_export.BigQueryExportSettings = proto.Field( + proto.MESSAGE, + number=3, + message=bigquery_export.BigQueryExportSettings, + ) + cloud_logging_settings: "CloudLoggingSettings" = proto.Field( + proto.MESSAGE, + number=4, + message="CloudLoggingSettings", + ) + conversation_logging_settings: "ConversationLoggingSettings" = proto.Field( + proto.MESSAGE, + number=5, + message="ConversationLoggingSettings", + ) + evaluation_audio_recording_config: "AudioRecordingConfig" = proto.Field( + proto.MESSAGE, + number=6, + message="AudioRecordingConfig", + ) + metric_analysis_settings: "MetricAnalysisSettings" = proto.Field( + proto.MESSAGE, + number=7, + message="MetricAnalysisSettings", + ) + + +class ErrorHandlingSettings(proto.Message): + r"""Settings to describe how errors should be handled in the app. + + Attributes: + error_handling_strategy (google.cloud.ces_v1beta.types.ErrorHandlingSettings.ErrorHandlingStrategy): + Optional. The strategy to use for error + handling. + """ + + class ErrorHandlingStrategy(proto.Enum): + r"""Defines the strategy for handling errors. + + Values: + ERROR_HANDLING_STRATEGY_UNSPECIFIED (0): + Unspecified error handling strategy. Defaults to + FALLBACK_RESPONSE. + NONE (1): + No specific handling is enabled. + FALLBACK_RESPONSE (2): + A fallback message will be returned to the + user in case of LLM errors. + """ + + ERROR_HANDLING_STRATEGY_UNSPECIFIED = 0 + NONE = 1 + FALLBACK_RESPONSE = 2 + + error_handling_strategy: ErrorHandlingStrategy = proto.Field( + proto.ENUM, + number=1, + enum=ErrorHandlingStrategy, + ) + + +class EvaluationMetricsThresholds(proto.Message): + r"""Threshold settings for metrics in an Evaluation. + + Attributes: + golden_evaluation_metrics_thresholds (google.cloud.ces_v1beta.types.EvaluationMetricsThresholds.GoldenEvaluationMetricsThresholds): + Optional. The golden evaluation metrics + thresholds. + hallucination_metric_behavior (google.cloud.ces_v1beta.types.EvaluationMetricsThresholds.HallucinationMetricBehavior): + Optional. Deprecated: Use + ``golden_hallucination_metric_behavior`` instead. The + hallucination metric behavior is currently used for golden + evaluations. + golden_hallucination_metric_behavior (google.cloud.ces_v1beta.types.EvaluationMetricsThresholds.HallucinationMetricBehavior): + Optional. The hallucination metric behavior + for golden evaluations. + scenario_hallucination_metric_behavior (google.cloud.ces_v1beta.types.EvaluationMetricsThresholds.HallucinationMetricBehavior): + Optional. The hallucination metric behavior + for scenario evaluations. + """ + + class HallucinationMetricBehavior(proto.Enum): + r"""The hallucination metric behavior. Regardless of the + behavior, the metric will always be calculated. The difference + is that when disabled, the metric is not used to calculate the + overall evaluation score. + + Values: + HALLUCINATION_METRIC_BEHAVIOR_UNSPECIFIED (0): + Unspecified hallucination metric behavior. + DISABLED (1): + Disable hallucination metric. + ENABLED (2): + Enable hallucination metric. + """ + + HALLUCINATION_METRIC_BEHAVIOR_UNSPECIFIED = 0 + DISABLED = 1 + ENABLED = 2 + + class GoldenEvaluationMetricsThresholds(proto.Message): + r"""Settings for golden evaluations. + + Attributes: + turn_level_metrics_thresholds (google.cloud.ces_v1beta.types.EvaluationMetricsThresholds.GoldenEvaluationMetricsThresholds.TurnLevelMetricsThresholds): + Optional. The turn level metrics thresholds. + expectation_level_metrics_thresholds (google.cloud.ces_v1beta.types.EvaluationMetricsThresholds.GoldenEvaluationMetricsThresholds.ExpectationLevelMetricsThresholds): + Optional. The expectation level metrics + thresholds. + tool_matching_settings (google.cloud.ces_v1beta.types.EvaluationMetricsThresholds.ToolMatchingSettings): + Optional. The tool matching settings. An + extra tool call is a tool call that is present + in the execution but does not match any tool + call in the golden expectation. + """ + + class TurnLevelMetricsThresholds(proto.Message): + r"""Turn level metrics thresholds. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + semantic_similarity_success_threshold (int): + Optional. The success threshold for semantic + similarity. Must be an integer between 0 and 4. + Default is >= 3. + + This field is a member of `oneof`_ ``_semantic_similarity_success_threshold``. + overall_tool_invocation_correctness_threshold (float): + Optional. The success threshold for overall + tool invocation correctness. Must be a float + between 0 and 1. Default is 1.0. + + This field is a member of `oneof`_ ``_overall_tool_invocation_correctness_threshold``. + semantic_similarity_channel (google.cloud.ces_v1beta.types.EvaluationMetricsThresholds.GoldenEvaluationMetricsThresholds.TurnLevelMetricsThresholds.SemanticSimilarityChannel): + Optional. The semantic similarity channel to + use for evaluation. + """ + + class SemanticSimilarityChannel(proto.Enum): + r"""Semantic similarity channel to use. + + Values: + SEMANTIC_SIMILARITY_CHANNEL_UNSPECIFIED (0): + Metric unspecified. Defaults to TEXT. + TEXT (1): + Use text semantic similarity. + AUDIO (2): + Use audio semantic similarity. + """ + + SEMANTIC_SIMILARITY_CHANNEL_UNSPECIFIED = 0 + TEXT = 1 + AUDIO = 2 + + semantic_similarity_success_threshold: int = proto.Field( + proto.INT32, + number=1, + optional=True, + ) + overall_tool_invocation_correctness_threshold: float = proto.Field( + proto.FLOAT, + number=2, + optional=True, + ) + semantic_similarity_channel: "EvaluationMetricsThresholds.GoldenEvaluationMetricsThresholds.TurnLevelMetricsThresholds.SemanticSimilarityChannel" = proto.Field( + proto.ENUM, + number=3, + enum="EvaluationMetricsThresholds.GoldenEvaluationMetricsThresholds.TurnLevelMetricsThresholds.SemanticSimilarityChannel", + ) + + class ExpectationLevelMetricsThresholds(proto.Message): + r"""Expectation level metrics thresholds. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + tool_invocation_parameter_correctness_threshold (float): + Optional. The success threshold for + individual tool invocation parameter + correctness. Must be a float between 0 and 1. + Default is 1.0. + + This field is a member of `oneof`_ ``_tool_invocation_parameter_correctness_threshold``. + """ + + tool_invocation_parameter_correctness_threshold: float = proto.Field( + proto.FLOAT, + number=1, + optional=True, + ) + + turn_level_metrics_thresholds: "EvaluationMetricsThresholds.GoldenEvaluationMetricsThresholds.TurnLevelMetricsThresholds" = proto.Field( + proto.MESSAGE, + number=1, + message="EvaluationMetricsThresholds.GoldenEvaluationMetricsThresholds.TurnLevelMetricsThresholds", + ) + expectation_level_metrics_thresholds: "EvaluationMetricsThresholds.GoldenEvaluationMetricsThresholds.ExpectationLevelMetricsThresholds" = proto.Field( + proto.MESSAGE, + number=2, + message="EvaluationMetricsThresholds.GoldenEvaluationMetricsThresholds.ExpectationLevelMetricsThresholds", + ) + tool_matching_settings: "EvaluationMetricsThresholds.ToolMatchingSettings" = ( + proto.Field( + proto.MESSAGE, + number=3, + message="EvaluationMetricsThresholds.ToolMatchingSettings", + ) + ) + + class ToolMatchingSettings(proto.Message): + r"""Settings for matching tool calls. + + Attributes: + extra_tool_call_behavior (google.cloud.ces_v1beta.types.EvaluationMetricsThresholds.ToolMatchingSettings.ExtraToolCallBehavior): + Optional. Behavior for extra tool calls. + Defaults to FAIL. + """ + + class ExtraToolCallBehavior(proto.Enum): + r"""Defines the behavior when an extra tool call is encountered. + An extra tool call is a tool call that is present in the + execution but does not match any tool call in the golden + expectation. + + Values: + EXTRA_TOOL_CALL_BEHAVIOR_UNSPECIFIED (0): + Unspecified behavior. Defaults to FAIL. + FAIL (1): + Fail the evaluation if an extra tool call is + encountered. + ALLOW (2): + Allow the extra tool call. + """ + + EXTRA_TOOL_CALL_BEHAVIOR_UNSPECIFIED = 0 + FAIL = 1 + ALLOW = 2 + + extra_tool_call_behavior: "EvaluationMetricsThresholds.ToolMatchingSettings.ExtraToolCallBehavior" = proto.Field( + proto.ENUM, + number=1, + enum="EvaluationMetricsThresholds.ToolMatchingSettings.ExtraToolCallBehavior", + ) + + golden_evaluation_metrics_thresholds: GoldenEvaluationMetricsThresholds = ( + proto.Field( + proto.MESSAGE, + number=1, + message=GoldenEvaluationMetricsThresholds, + ) + ) + hallucination_metric_behavior: HallucinationMetricBehavior = proto.Field( + proto.ENUM, + number=3, + enum=HallucinationMetricBehavior, + ) + golden_hallucination_metric_behavior: HallucinationMetricBehavior = proto.Field( + proto.ENUM, + number=5, + enum=HallucinationMetricBehavior, + ) + scenario_hallucination_metric_behavior: HallucinationMetricBehavior = proto.Field( + proto.ENUM, + number=4, + enum=HallucinationMetricBehavior, + ) + + +class EvaluationSettings(proto.Message): + r"""Settings for evaluation. + + Attributes: + scenario_conversation_initiator (google.cloud.ces_v1beta.types.EvaluationSettings.ScenarioConversationInitiator): + Optional. Who starts the conversation in a + scenario evaluation. + golden_run_method (google.cloud.ces_v1beta.types.GoldenRunMethod): + Optional. The default method used to run golden evaluations. + This will be used if no golden_run_method is specified in + the RunEvaluationRequest. + golden_evaluation_tool_call_behaviour (google.cloud.ces_v1beta.types.EvaluationToolCallBehaviour): + Optional. Configures the default tool call + behaviour for golden evaluations. + scenario_evaluation_tool_call_behaviour (google.cloud.ces_v1beta.types.EvaluationToolCallBehaviour): + Optional. Configures the default tool call + behaviour for scenario evaluations. + """ + + class ScenarioConversationInitiator(proto.Enum): + r"""Determines who starts the conversation in a scenario + evaluation session. + + Values: + SCENARIO_CONVERSATION_INITIATOR_UNSPECIFIED (0): + Unspecified. Defaults to USER. + USER (1): + The user starts the conversation. + AGENT (2): + The agent starts the conversation. + """ + + SCENARIO_CONVERSATION_INITIATOR_UNSPECIFIED = 0 + USER = 1 + AGENT = 2 + + scenario_conversation_initiator: ScenarioConversationInitiator = proto.Field( + proto.ENUM, + number=1, + enum=ScenarioConversationInitiator, + ) + golden_run_method: golden_run.GoldenRunMethod = proto.Field( + proto.ENUM, + number=4, + enum=golden_run.GoldenRunMethod, + ) + golden_evaluation_tool_call_behaviour: fakes.EvaluationToolCallBehaviour = ( + proto.Field( + proto.ENUM, + number=2, + enum=fakes.EvaluationToolCallBehaviour, + ) + ) + scenario_evaluation_tool_call_behaviour: fakes.EvaluationToolCallBehaviour = ( + proto.Field( + proto.ENUM, + number=3, + enum=fakes.EvaluationToolCallBehaviour, + ) + ) + + +class ClientCertificateSettings(proto.Message): + r"""Settings for custom client certificates. + + Attributes: + tls_certificate (str): + Required. The TLS certificate encoded in PEM + format. This string must include the begin + header and end footer lines. + private_key (str): + Required. The name of the SecretManager secret version + resource storing the private key encoded in PEM format. + Format: + ``projects/{project}/secrets/{secret}/versions/{version}`` + passphrase (str): + Optional. The name of the SecretManager secret version + resource storing the passphrase to decrypt the private key. + Should be left unset if the private key is not encrypted. + Format: + ``projects/{project}/secrets/{secret}/versions/{version}`` + """ + + tls_certificate: str = proto.Field( + proto.STRING, + number=1, + ) + private_key: str = proto.Field( + proto.STRING, + number=2, + ) + passphrase: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ConversationLoggingSettings(proto.Message): + r"""Settings to describe the conversation logging behaviors for + the app. + + Attributes: + disable_conversation_logging (bool): + Optional. Whether to disable conversation + logging for the sessions. + """ + + disable_conversation_logging: bool = proto.Field( + proto.BOOL, + number=1, + ) + + +class CloudLoggingSettings(proto.Message): + r"""Settings to describe the Cloud Logging behaviors for the app. + + Attributes: + enable_cloud_logging (bool): + Optional. Whether to enable Cloud Logging for + the sessions. + """ + + enable_cloud_logging: bool = proto.Field( + proto.BOOL, + number=1, + ) + + +class AudioRecordingConfig(proto.Message): + r"""Configuration for how the audio interactions should be + recorded. + + Attributes: + gcs_bucket (str): + Optional. The `Cloud + Storage `__ bucket to + store the session audio recordings. The URI must start with + "gs://". + + Please choose a bucket location that meets your data + residency requirements. + + Note: If the Cloud Storage bucket is in a different project + from the app, you should grant ``storage.objects.create`` + permission to the CES service agent + ``service-@gcp-sa-ces.iam.gserviceaccount.com``. + gcs_path_prefix (str): + Optional. The Cloud Storage path prefix for audio + recordings. + + This prefix can include the following placeholders, which + will be dynamically substituted at serving time: + + - $project: project ID + - $location: app location + - $app: app ID + - $date: session date in YYYY-MM-DD format + - $session: session ID + + If the path prefix is not specified, the default prefix + ``$project/$location/$app/$date/$session/`` will be used. + """ + + gcs_bucket: str = proto.Field( + proto.STRING, + number=1, + ) + gcs_path_prefix: str = proto.Field( + proto.STRING, + number=2, + ) + + +class RedactionConfig(proto.Message): + r"""Configuration to instruct how sensitive data should be + handled. + + Attributes: + enable_redaction (bool): + Optional. If true, redaction will be applied + in various logging scenarios, including + conversation history, Cloud Logging and audio + recording. + inspect_template (str): + Optional. `DLP `__ + inspect template name to configure detection of sensitive + data types. + + Format: + ``projects/{project}/locations/{location}/inspectTemplates/{inspect_template}`` + deidentify_template (str): + Optional. `DLP `__ + deidentify template name to instruct on how to de-identify + content. + + Format: + ``projects/{project}/locations/{location}/deidentifyTemplates/{deidentify_template}`` + """ + + enable_redaction: bool = proto.Field( + proto.BOOL, + number=1, + ) + inspect_template: str = proto.Field( + proto.STRING, + number=2, + ) + deidentify_template: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DataStoreSettings(proto.Message): + r"""Data store related settings for the app. + + Attributes: + engines (MutableSequence[google.cloud.ces_v1beta.types.DataStoreSettings.Engine]): + Output only. The engines for the app. + """ + + class Engine(proto.Message): + r"""An engine to which the data stores are connected. + See Vertex AI Search: + + https://cloud.google.com/generative-ai-app-builder/docs/enterprise-search-introduction. + + Attributes: + name (str): + Output only. The resource name of the engine. Format: + ``projects/{project}/locations/{location}/collections/{collection}/engines/{engine}`` + type_ (google.cloud.ces_v1beta.types.DataStoreSettings.Engine.Type): + Output only. The type of the engine. + """ + + class Type(proto.Enum): + r"""The type of the engine. + See the documentation available at + https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/SolutionType + and + https://cloud.google.com/generative-ai-app-builder/docs/create-datastore-ingest. + + Values: + TYPE_UNSPECIFIED (0): + Unspecified engine type. + ENGINE_TYPE_SEARCH (1): + The SOLUTION_TYPE_SEARCH engine for the app. All connector + data stores added to the app will be added to this engine. + ENGINE_TYPE_CHAT (2): + Chat engine type. The SOLUTION_TYPE_CHAT engine for the app. + All connector data stores added to the app will be added to + this engine. + """ + + TYPE_UNSPECIFIED = 0 + ENGINE_TYPE_SEARCH = 1 + ENGINE_TYPE_CHAT = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + type_: "DataStoreSettings.Engine.Type" = proto.Field( + proto.ENUM, + number=2, + enum="DataStoreSettings.Engine.Type", + ) + + engines: MutableSequence[Engine] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=Engine, + ) + + +class EvaluationPersona(proto.Message): + r"""A persona represents an end user in an evaluation. + + Attributes: + name (str): + Required. The unique identifier of the persona. Format: + ``projects/{project}/locations/{location}/apps/{app}/evaluationPersonas/{evaluationPersona}`` + description (str): + Optional. The description of the persona. + display_name (str): + Required. The display name of the persona. + Unique within an app. + personality (str): + Required. An instruction for the agent on how + to behave in the evaluation. + speech_config (google.cloud.ces_v1beta.types.EvaluationPersona.SpeechConfig): + Optional. Configuration for how the persona + sounds (TTS settings). + """ + + class SpeechConfig(proto.Message): + r"""Configuration for Text-to-Speech generation. + + Attributes: + speaking_rate (float): + Optional. The speaking rate. 1.0 is normal. + Lower is slower (e.g., 0.8), higher is faster + (e.g., 1.5). Useful for testing how the agent + handles fast talkers. + environment (google.cloud.ces_v1beta.types.EvaluationPersona.SpeechConfig.BackgroundEnvironment): + Optional. The simulated audio environment. + voice_id (str): + Optional. The specific voice + identifier/accent to use. Example: + "en-US-Wavenet-D" or "en-GB-Standard-A". + """ + + class BackgroundEnvironment(proto.Enum): + r"""Simulated audio environment. + + Values: + BACKGROUND_ENVIRONMENT_UNSPECIFIED (0): + Background environment unspecified. + CALL_CENTER (3): + Call center environment. + TRAFFIC (4): + Traffic noise environment. + KIDS_NOISE (5): + Kids noise environment. + CAFE (6): + Cafe environment. + """ + + BACKGROUND_ENVIRONMENT_UNSPECIFIED = 0 + CALL_CENTER = 3 + TRAFFIC = 4 + KIDS_NOISE = 5 + CAFE = 6 + + speaking_rate: float = proto.Field( + proto.DOUBLE, + number=1, + ) + environment: "EvaluationPersona.SpeechConfig.BackgroundEnvironment" = ( + proto.Field( + proto.ENUM, + number=2, + enum="EvaluationPersona.SpeechConfig.BackgroundEnvironment", + ) + ) + voice_id: str = proto.Field( + proto.STRING, + number=3, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + personality: str = proto.Field( + proto.STRING, + number=4, + ) + speech_config: SpeechConfig = proto.Field( + proto.MESSAGE, + number=5, + message=SpeechConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/app_version.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/app_version.py new file mode 100644 index 000000000000..f298d03d678b --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/app_version.py @@ -0,0 +1,148 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.ces_v1beta.types import agent, example, guardrail, tool, toolset +from google.cloud.ces_v1beta.types import app as gcc_app + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "AppSnapshot", + "AppVersion", + }, +) + + +class AppSnapshot(proto.Message): + r"""A snapshot of the app. + + Attributes: + app (google.cloud.ces_v1beta.types.App): + Optional. The basic settings for the app. + agents (MutableSequence[google.cloud.ces_v1beta.types.Agent]): + Optional. List of agents in the app. + tools (MutableSequence[google.cloud.ces_v1beta.types.Tool]): + Optional. List of tools in the app. + examples (MutableSequence[google.cloud.ces_v1beta.types.Example]): + Optional. List of examples in the app. + guardrails (MutableSequence[google.cloud.ces_v1beta.types.Guardrail]): + Optional. List of guardrails in the app. + toolsets (MutableSequence[google.cloud.ces_v1beta.types.Toolset]): + Optional. List of toolsets in the app. + """ + + app: gcc_app.App = proto.Field( + proto.MESSAGE, + number=1, + message=gcc_app.App, + ) + agents: MutableSequence[agent.Agent] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=agent.Agent, + ) + tools: MutableSequence[tool.Tool] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=tool.Tool, + ) + examples: MutableSequence[example.Example] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=example.Example, + ) + guardrails: MutableSequence[guardrail.Guardrail] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=guardrail.Guardrail, + ) + toolsets: MutableSequence[toolset.Toolset] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=toolset.Toolset, + ) + + +class AppVersion(proto.Message): + r"""In Customer Engagement Suite (CES), an app version is a + snapshot of the app at a specific point in time. It is immutable + and cannot be modified once created. + + Attributes: + name (str): + Identifier. The unique identifier of the app version. + Format: + ``projects/{project}/locations/{location}/apps/{app}/versions/{version}`` + display_name (str): + Optional. The display name of the app + version. + description (str): + Optional. The description of the app version. + creator (str): + Output only. Email of the user who created + the app version. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the app version + was created. + snapshot (google.cloud.ces_v1beta.types.AppSnapshot): + Output only. The snapshot of the app when the + version is created. + etag (str): + Output only. Etag used to ensure the object + hasn't changed during a read-modify-write + operation. If the etag is empty, the update will + overwrite any concurrent changes. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + creator: str = proto.Field( + proto.STRING, + number=4, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + snapshot: "AppSnapshot" = proto.Field( + proto.MESSAGE, + number=8, + message="AppSnapshot", + ) + etag: str = proto.Field( + proto.STRING, + number=7, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/auth.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/auth.py new file mode 100644 index 000000000000..902bce4e3f44 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/auth.py @@ -0,0 +1,355 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "ApiKeyConfig", + "OAuthConfig", + "ServiceAgentIdTokenAuthConfig", + "ServiceAccountAuthConfig", + "BearerTokenConfig", + "EndUserAuthConfig", + "ApiAuthentication", + }, +) + + +class ApiKeyConfig(proto.Message): + r"""Configurations for authentication with API key. + + Attributes: + key_name (str): + Required. The parameter name or the header + name of the API key. E.g., If the API request is + "https://example.com/act?X-Api-Key=", + "X-Api-Key" would be the parameter name. + api_key_secret_version (str): + Required. The name of the SecretManager secret version + resource storing the API key. Format: + ``projects/{project}/secrets/{secret}/versions/{version}`` + + Note: You should grant + ``roles/secretmanager.secretAccessor`` role to the CES + service agent + ``service-@gcp-sa-ces.iam.gserviceaccount.com``. + request_location (google.cloud.ces_v1beta.types.ApiKeyConfig.RequestLocation): + Required. Key location in the request. + """ + + class RequestLocation(proto.Enum): + r"""The location of the API key in the request. + + Values: + REQUEST_LOCATION_UNSPECIFIED (0): + Unspecified. This value should not be used. + HEADER (1): + Represents the key in http header. + QUERY_STRING (2): + Represents the key in query string. + """ + + REQUEST_LOCATION_UNSPECIFIED = 0 + HEADER = 1 + QUERY_STRING = 2 + + key_name: str = proto.Field( + proto.STRING, + number=1, + ) + api_key_secret_version: str = proto.Field( + proto.STRING, + number=2, + ) + request_location: RequestLocation = proto.Field( + proto.ENUM, + number=3, + enum=RequestLocation, + ) + + +class OAuthConfig(proto.Message): + r"""Configurations for authentication with OAuth. + + Attributes: + oauth_grant_type (google.cloud.ces_v1beta.types.OAuthConfig.OauthGrantType): + Required. OAuth grant types. + client_id (str): + Required. The client ID from the OAuth + provider. + client_secret_version (str): + Required. The name of the SecretManager secret version + resource storing the client secret. Format: + ``projects/{project}/secrets/{secret}/versions/{version}`` + + Note: You should grant + ``roles/secretmanager.secretAccessor`` role to the CES + service agent + ``service-@gcp-sa-ces.iam.gserviceaccount.com``. + token_endpoint (str): + Required. The token endpoint in the OAuth + provider to exchange for an access token. + scopes (MutableSequence[str]): + Optional. The OAuth scopes to grant. + """ + + class OauthGrantType(proto.Enum): + r"""OAuth grant types. Only `client credential + grant `__ is + supported. + + Values: + OAUTH_GRANT_TYPE_UNSPECIFIED (0): + Unspecified. Defaults to CLIENT_CREDENTIAL. + CLIENT_CREDENTIAL (1): + Represents the `client credential + flow `__. + """ + + OAUTH_GRANT_TYPE_UNSPECIFIED = 0 + CLIENT_CREDENTIAL = 1 + + oauth_grant_type: OauthGrantType = proto.Field( + proto.ENUM, + number=1, + enum=OauthGrantType, + ) + client_id: str = proto.Field( + proto.STRING, + number=2, + ) + client_secret_version: str = proto.Field( + proto.STRING, + number=3, + ) + token_endpoint: str = proto.Field( + proto.STRING, + number=4, + ) + scopes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + + +class ServiceAgentIdTokenAuthConfig(proto.Message): + r"""Configurations for authentication with `ID + token `__ + generated from service agent. + + """ + + +class ServiceAccountAuthConfig(proto.Message): + r"""Configurations for authentication using a custom service + account. + + Attributes: + service_account (str): + Required. The email address of the service account used for + authentication. CES uses this service account to exchange an + access token and the access token is then sent in the + ``Authorization`` header of the request. + + The service account must have the + ``roles/iam.serviceAccountTokenCreator`` role granted to the + CES service agent + ``service-@gcp-sa-ces.iam.gserviceaccount.com``. + scopes (MutableSequence[str]): + Optional. The OAuth scopes to grant. If not specified, the + default scope + ``https://www.googleapis.com/auth/cloud-platform`` is used. + """ + + service_account: str = proto.Field( + proto.STRING, + number=1, + ) + scopes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class BearerTokenConfig(proto.Message): + r"""Configurations for authentication with a bearer token. + + Attributes: + token (str): + Required. The bearer token. Must be in the format + ``$context.variables.``. + """ + + token: str = proto.Field( + proto.STRING, + number=1, + ) + + +class EndUserAuthConfig(proto.Message): + r"""End-user authentication configuration used for Connection calls. The + field values must be the names of context variables in the format + ``$context.variables.``. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + oauth2_auth_code_config (google.cloud.ces_v1beta.types.EndUserAuthConfig.Oauth2AuthCodeConfig): + Oauth 2.0 Authorization Code authentication. + + This field is a member of `oneof`_ ``auth_config``. + oauth2_jwt_bearer_config (google.cloud.ces_v1beta.types.EndUserAuthConfig.Oauth2JwtBearerConfig): + JWT Profile Oauth 2.0 Authorization Grant + authentication. + + This field is a member of `oneof`_ ``auth_config``. + """ + + class Oauth2AuthCodeConfig(proto.Message): + r"""Oauth 2.0 Authorization Code authentication configuration. + + Attributes: + oauth_token (str): + Required. Oauth token parameter name to pass through. Must + be in the format ``$context.variables.``. + """ + + oauth_token: str = proto.Field( + proto.STRING, + number=1, + ) + + class Oauth2JwtBearerConfig(proto.Message): + r"""JWT Profile Oauth 2.0 Authorization Grant authentication + configuration. + + Attributes: + issuer (str): + Required. Issuer parameter name to pass through. Must be in + the format ``$context.variables.``. + subject (str): + Required. Subject parameter name to pass through. Must be in + the format ``$context.variables.``. + client_key (str): + Required. Client parameter name to pass through. Must be in + the format ``$context.variables.``. + """ + + issuer: str = proto.Field( + proto.STRING, + number=1, + ) + subject: str = proto.Field( + proto.STRING, + number=2, + ) + client_key: str = proto.Field( + proto.STRING, + number=3, + ) + + oauth2_auth_code_config: Oauth2AuthCodeConfig = proto.Field( + proto.MESSAGE, + number=2, + oneof="auth_config", + message=Oauth2AuthCodeConfig, + ) + oauth2_jwt_bearer_config: Oauth2JwtBearerConfig = proto.Field( + proto.MESSAGE, + number=3, + oneof="auth_config", + message=Oauth2JwtBearerConfig, + ) + + +class ApiAuthentication(proto.Message): + r"""Authentication information required for API calls. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + api_key_config (google.cloud.ces_v1beta.types.ApiKeyConfig): + Optional. Config for API key auth. + + This field is a member of `oneof`_ ``auth_config``. + oauth_config (google.cloud.ces_v1beta.types.OAuthConfig): + Optional. Config for OAuth. + + This field is a member of `oneof`_ ``auth_config``. + service_agent_id_token_auth_config (google.cloud.ces_v1beta.types.ServiceAgentIdTokenAuthConfig): + Optional. Config for ID token auth generated + from CES service agent. + + This field is a member of `oneof`_ ``auth_config``. + service_account_auth_config (google.cloud.ces_v1beta.types.ServiceAccountAuthConfig): + Optional. Config for service account + authentication. + + This field is a member of `oneof`_ ``auth_config``. + bearer_token_config (google.cloud.ces_v1beta.types.BearerTokenConfig): + Optional. Config for bearer token auth. + + This field is a member of `oneof`_ ``auth_config``. + """ + + api_key_config: "ApiKeyConfig" = proto.Field( + proto.MESSAGE, + number=1, + oneof="auth_config", + message="ApiKeyConfig", + ) + oauth_config: "OAuthConfig" = proto.Field( + proto.MESSAGE, + number=2, + oneof="auth_config", + message="OAuthConfig", + ) + service_agent_id_token_auth_config: "ServiceAgentIdTokenAuthConfig" = proto.Field( + proto.MESSAGE, + number=3, + oneof="auth_config", + message="ServiceAgentIdTokenAuthConfig", + ) + service_account_auth_config: "ServiceAccountAuthConfig" = proto.Field( + proto.MESSAGE, + number=4, + oneof="auth_config", + message="ServiceAccountAuthConfig", + ) + bearer_token_config: "BearerTokenConfig" = proto.Field( + proto.MESSAGE, + number=5, + oneof="auth_config", + message="BearerTokenConfig", + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/bigquery_export.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/bigquery_export.py new file mode 100644 index 000000000000..c9147c9de09c --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/bigquery_export.py @@ -0,0 +1,65 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "BigQueryExportSettings", + }, +) + + +class BigQueryExportSettings(proto.Message): + r"""Settings to describe the BigQuery export behaviors for the + app. + + Attributes: + enabled (bool): + Optional. Indicates whether the BigQuery + export is enabled. + project (str): + Optional. The project ID of the BigQuery dataset to export + the data to. + + Note: If the BigQuery dataset is in a different project from + the app, you should grant ``roles/bigquery.admin`` role to + the CES service agent + ``service-@gcp-sa-ces.iam.gserviceaccount.com``. + dataset (str): + Optional. The BigQuery dataset to export the + data to. + """ + + enabled: bool = proto.Field( + proto.BOOL, + number=1, + ) + project: str = proto.Field( + proto.STRING, + number=2, + ) + dataset: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/changelog.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/changelog.py new file mode 100644 index 000000000000..08ff4d247958 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/changelog.py @@ -0,0 +1,130 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import google.protobuf.struct_pb2 as struct_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "Changelog", + }, +) + + +class Changelog(proto.Message): + r"""Changelogs represent a change made to the app or to an + resource within the app. + + Attributes: + name (str): + Identifier. The unique identifier of the changelog. Format: + ``projects/{project}/locations/{location}/apps/{app}/changelogs/{changelog}`` + author (str): + Output only. Email address of the change + author. + display_name (str): + Output only. Display name of the change. It + typically should be the display name of the + resource that was changed. + description (str): + Output only. Description of the change. which + typically captures the changed fields in the + resource. + resource (str): + Output only. The resource that was changed. + resource_type (str): + Output only. The type of the resource that + was changed. + action (str): + Output only. The action that was performed on + the resource. + original_resource (google.protobuf.struct_pb2.Struct): + Output only. The original resource before the + change. + new_resource (google.protobuf.struct_pb2.Struct): + Output only. The new resource after the + change. + dependent_resources (MutableSequence[google.protobuf.struct_pb2.Struct]): + Output only. The dependent resources that + were changed. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the change was + made. + sequence_number (int): + Output only. The monotonically increasing + sequence number of the changelog. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + author: str = proto.Field( + proto.STRING, + number=2, + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + description: str = proto.Field( + proto.STRING, + number=11, + ) + resource: str = proto.Field( + proto.STRING, + number=4, + ) + resource_type: str = proto.Field( + proto.STRING, + number=5, + ) + action: str = proto.Field( + proto.STRING, + number=6, + ) + original_resource: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=7, + message=struct_pb2.Struct, + ) + new_resource: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=8, + message=struct_pb2.Struct, + ) + dependent_resources: MutableSequence[struct_pb2.Struct] = proto.RepeatedField( + proto.MESSAGE, + number=9, + message=struct_pb2.Struct, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + sequence_number: int = proto.Field( + proto.INT64, + number=12, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/client_function.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/client_function.py new file mode 100644 index 000000000000..ee7a61e55dd6 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/client_function.py @@ -0,0 +1,73 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.ces_v1beta.types import schema + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "ClientFunction", + }, +) + + +class ClientFunction(proto.Message): + r"""Represents a client-side function that the agent can invoke. When + the tool is chosen by the agent, control is handed off to the + client. The client is responsible for executing the function and + returning the result as a + [ToolResponse][google.cloud.ces.v1beta.ToolResponse] to continue the + interaction with the agent. + + Attributes: + name (str): + Required. The function name. + description (str): + Optional. The function description. + parameters (google.cloud.ces_v1beta.types.Schema): + Optional. The schema of the function + parameters. + response (google.cloud.ces_v1beta.types.Schema): + Optional. The schema of the function + response. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + parameters: schema.Schema = proto.Field( + proto.MESSAGE, + number=3, + message=schema.Schema, + ) + response: schema.Schema = proto.Field( + proto.MESSAGE, + number=4, + message=schema.Schema, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/common.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/common.py new file mode 100644 index 000000000000..dc914d22e9e8 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/common.py @@ -0,0 +1,624 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.struct_pb2 as struct_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "ExecutionType", + "Callback", + "ModelSettings", + "TriggerAction", + "TlsConfig", + "ServiceDirectoryConfig", + "ChannelProfile", + "Span", + }, +) + + +class ExecutionType(proto.Enum): + r"""The execution type of the tool or toolset. + + Values: + EXECUTION_TYPE_UNSPECIFIED (0): + The execution type is unspecified. Defaults to + ``SYNCHRONOUS`` if unspecified. + SYNCHRONOUS (1): + The tool is executed synchronously. The + session is blocked until the tool returns. + ASYNCHRONOUS (2): + The tool is executed asynchronously. The + session will continue while the tool is + executing. + """ + + EXECUTION_TYPE_UNSPECIFIED = 0 + SYNCHRONOUS = 1 + ASYNCHRONOUS = 2 + + +class Callback(proto.Message): + r"""A callback defines the custom logic to be executed at various + stages of agent interaction. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + python_code (str): + Required. The python code to execute for the + callback. + + This field is a member of `oneof`_ ``callback``. + description (str): + Optional. Human-readable description of the + callback. + disabled (bool): + Optional. Whether the callback is disabled. + Disabled callbacks are ignored by the agent. + proactive_execution_enabled (bool): + Optional. If enabled, the callback will also be executed on + intermediate model outputs. This setting only affects after + model callback. **ENABLE WITH CAUTION**. Typically after + model callback only needs to be executed after receiving all + model responses. Enabling proactive execution may have + negative implication on the execution cost and latency, and + should only be enabled in rare situations. + """ + + python_code: str = proto.Field( + proto.STRING, + number=1, + oneof="callback", + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + disabled: bool = proto.Field( + proto.BOOL, + number=2, + ) + proactive_execution_enabled: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class ModelSettings(proto.Message): + r"""Model settings contains various configurations for the LLM + model. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + model (str): + Optional. The LLM model that the agent should + use. If not set, the agent will inherit the + model from its parent agent. + temperature (float): + Optional. If set, this temperature will be + used for the LLM model. Temperature controls the + randomness of the model's responses. Lower + temperatures produce responses that are more + predictable. Higher temperatures produce + responses that are more creative. + + This field is a member of `oneof`_ ``_temperature``. + """ + + model: str = proto.Field( + proto.STRING, + number=1, + ) + temperature: float = proto.Field( + proto.DOUBLE, + number=2, + optional=True, + ) + + +class TriggerAction(proto.Message): + r"""Action that is taken when a certain precondition is met. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + respond_immediately (google.cloud.ces_v1beta.types.TriggerAction.RespondImmediately): + Optional. Immediately respond with a + preconfigured response. + + This field is a member of `oneof`_ ``action``. + transfer_agent (google.cloud.ces_v1beta.types.TriggerAction.TransferAgent): + Optional. Transfer the conversation to a + different agent. + + This field is a member of `oneof`_ ``action``. + generative_answer (google.cloud.ces_v1beta.types.TriggerAction.GenerativeAnswer): + Optional. Respond with a generative answer. + + This field is a member of `oneof`_ ``action``. + """ + + class Response(proto.Message): + r"""Represents a response from the agent. + + Attributes: + text (str): + Required. Text for the agent to respond with. + disabled (bool): + Optional. Whether the response is disabled. + Disabled responses are not used by the agent. + """ + + text: str = proto.Field( + proto.STRING, + number=1, + ) + disabled: bool = proto.Field( + proto.BOOL, + number=2, + ) + + class RespondImmediately(proto.Message): + r"""The agent will immediately respond with a preconfigured + response. + + Attributes: + responses (MutableSequence[google.cloud.ces_v1beta.types.TriggerAction.Response]): + Required. The canned responses for the agent + to choose from. The response is chosen randomly. + """ + + responses: MutableSequence["TriggerAction.Response"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="TriggerAction.Response", + ) + + class GenerativeAnswer(proto.Message): + r"""The agent will immediately respond with a generative answer. + + Attributes: + prompt (str): + Required. The prompt to use for the + generative answer. + """ + + prompt: str = proto.Field( + proto.STRING, + number=1, + ) + + class TransferAgent(proto.Message): + r"""The agent will transfer the conversation to a different + agent. + + Attributes: + agent (str): + Required. The name of the agent to transfer the conversation + to. The agent must be in the same app as the current agent. + Format: + ``projects/{project}/locations/{location}/apps/{app}/agents/{agent}`` + """ + + agent: str = proto.Field( + proto.STRING, + number=1, + ) + + respond_immediately: RespondImmediately = proto.Field( + proto.MESSAGE, + number=1, + oneof="action", + message=RespondImmediately, + ) + transfer_agent: TransferAgent = proto.Field( + proto.MESSAGE, + number=2, + oneof="action", + message=TransferAgent, + ) + generative_answer: GenerativeAnswer = proto.Field( + proto.MESSAGE, + number=3, + oneof="action", + message=GenerativeAnswer, + ) + + +class TlsConfig(proto.Message): + r"""The TLS configuration. + + Attributes: + ca_certs (MutableSequence[google.cloud.ces_v1beta.types.TlsConfig.CaCert]): + Required. Specifies a list of allowed custom + CA certificates for HTTPS verification. + """ + + class CaCert(proto.Message): + r"""The CA certificate. + + Attributes: + display_name (str): + Required. The name of the allowed custom CA + certificates. This can be used to disambiguate + the custom CA certificates. + cert (bytes): + Required. The allowed custom CA certificates + (in DER format) for HTTPS verification. This + overrides the default SSL trust store. If this + is empty or unspecified, CES will use Google's + default trust store to verify certificates. N.B. + Make sure the HTTPS server certificates are + signed with "subject alt name". For instance a + certificate can be self-signed using the + following command, openssl x509 -req -days + 200 -in example.com.csr \ -signkey + example.com.key \ + -out example.com.crt \ + -extfile <(printf + "\nsubjectAltName='DNS:www.example.com'") + """ + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + cert: bytes = proto.Field( + proto.BYTES, + number=2, + ) + + ca_certs: MutableSequence[CaCert] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=CaCert, + ) + + +class ServiceDirectoryConfig(proto.Message): + r"""Configuration for tools using Service Directory. + + Attributes: + service (str): + Required. The name of `Service + Directory `__ + service. Format: + ``projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}``. + Location of the service directory must be the same as the + location of the app. + """ + + service: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ChannelProfile(proto.Message): + r"""A ChannelProfile configures the agent's behavior for a + specific communication channel, such as web UI or telephony. + + Attributes: + profile_id (str): + Optional. The unique identifier of the + channel profile. + channel_type (google.cloud.ces_v1beta.types.ChannelProfile.ChannelType): + Optional. The type of the channel profile. + persona_property (google.cloud.ces_v1beta.types.ChannelProfile.PersonaProperty): + Optional. The persona property of the channel + profile. + disable_dtmf (bool): + Optional. Whether to disable DTMF (dual-tone + multi-frequency). + disable_barge_in_control (bool): + Optional. Whether to disable user barge-in control in the + conversation. + + - **true**: User interruptions are disabled while the agent + is speaking. + - **false**: The agent retains automatic control over when + the user can interrupt. + web_widget_config (google.cloud.ces_v1beta.types.ChannelProfile.WebWidgetConfig): + Optional. The configuration for the web + widget. + noise_suppression_level (str): + Optional. The noise suppression level of the channel + profile. Available values are "low", "moderate", "high", + "very_high". + """ + + class ChannelType(proto.Enum): + r"""The type of the channel profile. + + Values: + UNKNOWN (0): + Unknown channel type. + WEB_UI (2): + Web UI channel. + API (3): + API channel. + TWILIO (4): + Twilio channel. + GOOGLE_TELEPHONY_PLATFORM (5): + Google Telephony Platform channel. + CONTACT_CENTER_AS_A_SERVICE (6): + Contact Center as a Service (CCaaS) channel. + FIVE9 (7): + Five9 channel. + CONTACT_CENTER_INTEGRATION (8): + Third party contact center integration + channel. + """ + + UNKNOWN = 0 + WEB_UI = 2 + API = 3 + TWILIO = 4 + GOOGLE_TELEPHONY_PLATFORM = 5 + CONTACT_CENTER_AS_A_SERVICE = 6 + FIVE9 = 7 + CONTACT_CENTER_INTEGRATION = 8 + + class PersonaProperty(proto.Message): + r"""Represents the persona property of a channel. + + Attributes: + persona (google.cloud.ces_v1beta.types.ChannelProfile.PersonaProperty.Persona): + Optional. The persona of the channel. + """ + + class Persona(proto.Enum): + r"""The persona of the channel. + + Values: + UNKNOWN (0): + UNKNOWN persona. + CONCISE (1): + The agent keeps the responses concise and to + the point + CHATTY (2): + The agent provides additional context, + explanations, and details + """ + + UNKNOWN = 0 + CONCISE = 1 + CHATTY = 2 + + persona: "ChannelProfile.PersonaProperty.Persona" = proto.Field( + proto.ENUM, + number=1, + enum="ChannelProfile.PersonaProperty.Persona", + ) + + class WebWidgetConfig(proto.Message): + r"""Message for configuration for the web widget. + + Attributes: + modality (google.cloud.ces_v1beta.types.ChannelProfile.WebWidgetConfig.Modality): + Optional. The modality of the web widget. + theme (google.cloud.ces_v1beta.types.ChannelProfile.WebWidgetConfig.Theme): + Optional. The theme of the web widget. + web_widget_title (str): + Optional. The title of the web widget. + security_settings (google.cloud.ces_v1beta.types.ChannelProfile.WebWidgetConfig.SecuritySettings): + Optional. The security settings of the web + widget. + """ + + class Modality(proto.Enum): + r"""Modality of the web widget. + + Values: + MODALITY_UNSPECIFIED (0): + Unknown modality. + CHAT_AND_VOICE (1): + Widget supports both chat and voice input. + VOICE_ONLY (2): + Widget supports only voice input. + CHAT_ONLY (3): + Widget supports only chat input. + """ + + MODALITY_UNSPECIFIED = 0 + CHAT_AND_VOICE = 1 + VOICE_ONLY = 2 + CHAT_ONLY = 3 + + class Theme(proto.Enum): + r"""Theme of the web widget. + + Values: + THEME_UNSPECIFIED (0): + Unknown theme. + LIGHT (1): + Light theme. + DARK (2): + Dark theme. + """ + + THEME_UNSPECIFIED = 0 + LIGHT = 1 + DARK = 2 + + class SecuritySettings(proto.Message): + r"""Security settings for the web widget. + + Attributes: + enable_public_access (bool): + Optional. Indicates whether public access to the web widget + is enabled. If ``true``, the web widget will be publicly + accessible. If ``false``, the web widget must be integrated + with your own authentication and authorization system to + return valid credentials for accessing the CES agent. + enable_origin_check (bool): + Optional. Indicates whether origin check for the web widget + is enabled. If ``true``, the web widget will check the + origin of the website that loads the web widget and only + allow it to be loaded in the same origin or any of the + allowed origins. + allowed_origins (MutableSequence[str]): + Optional. The origins that are allowed to + host the web widget. An origin is defined by RFC + 6454. If empty, all origins are allowed. A + maximum of 100 origins is allowed. Example: + "https://example.com". + enable_recaptcha (bool): + Optional. Indicates whether reCAPTCHA + verification for the web widget is enabled. + """ + + enable_public_access: bool = proto.Field( + proto.BOOL, + number=1, + ) + enable_origin_check: bool = proto.Field( + proto.BOOL, + number=4, + ) + allowed_origins: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + enable_recaptcha: bool = proto.Field( + proto.BOOL, + number=3, + ) + + modality: "ChannelProfile.WebWidgetConfig.Modality" = proto.Field( + proto.ENUM, + number=1, + enum="ChannelProfile.WebWidgetConfig.Modality", + ) + theme: "ChannelProfile.WebWidgetConfig.Theme" = proto.Field( + proto.ENUM, + number=2, + enum="ChannelProfile.WebWidgetConfig.Theme", + ) + web_widget_title: str = proto.Field( + proto.STRING, + number=3, + ) + security_settings: "ChannelProfile.WebWidgetConfig.SecuritySettings" = ( + proto.Field( + proto.MESSAGE, + number=4, + message="ChannelProfile.WebWidgetConfig.SecuritySettings", + ) + ) + + profile_id: str = proto.Field( + proto.STRING, + number=1, + ) + channel_type: ChannelType = proto.Field( + proto.ENUM, + number=3, + enum=ChannelType, + ) + persona_property: PersonaProperty = proto.Field( + proto.MESSAGE, + number=2, + message=PersonaProperty, + ) + disable_dtmf: bool = proto.Field( + proto.BOOL, + number=4, + ) + disable_barge_in_control: bool = proto.Field( + proto.BOOL, + number=5, + ) + web_widget_config: WebWidgetConfig = proto.Field( + proto.MESSAGE, + number=7, + message=WebWidgetConfig, + ) + noise_suppression_level: str = proto.Field( + proto.STRING, + number=8, + ) + + +class Span(proto.Message): + r"""A span is a unit of work or a single operation during the + request processing. + + Attributes: + name (str): + Output only. The name of the span. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The start time of the span. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The end time of the span. + duration (google.protobuf.duration_pb2.Duration): + Output only. The duration of the span. + attributes (google.protobuf.struct_pb2.Struct): + Output only. Key-value attributes associated + with the span. + child_spans (MutableSequence[google.cloud.ces_v1beta.types.Span]): + Output only. The child spans that are nested + under this span. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, + ) + attributes: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=4, + message=struct_pb2.Struct, + ) + child_spans: MutableSequence["Span"] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message="Span", + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/connector_tool.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/connector_tool.py new file mode 100644 index 000000000000..b4ddd618ee0a --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/connector_tool.py @@ -0,0 +1,190 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.ces_v1beta.types import auth + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "Action", + "ConnectorTool", + }, +) + + +class Action(proto.Message): + r"""Configuration of an Action for the tool to use. + Note: This can be either an Action or an Operation. See + https://cloud.google.com/integration-connectors/docs/entities-operation-action + for details. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + connection_action_id (str): + ID of a Connection action for the tool to + use. + + This field is a member of `oneof`_ ``action_spec``. + entity_operation (google.cloud.ces_v1beta.types.Action.EntityOperation): + Entity operation configuration for the tool + to use. + + This field is a member of `oneof`_ ``action_spec``. + input_fields (MutableSequence[str]): + Optional. Entity fields to use as inputs for + the operation. If no fields are specified, all + fields of the Entity will be used. + output_fields (MutableSequence[str]): + Optional. Entity fields to return from the + operation. If no fields are specified, all + fields of the Entity will be returned. + """ + + class EntityOperation(proto.Message): + r"""Entity CRUD operation specification. + + Attributes: + entity_id (str): + Required. ID of the entity. + operation (google.cloud.ces_v1beta.types.Action.EntityOperation.OperationType): + Required. Operation to perform on the entity. + """ + + class OperationType(proto.Enum): + r"""The operation to perform on the entity. + + Values: + OPERATION_TYPE_UNSPECIFIED (0): + Operation type unspecified. Invalid, + ConnectorTool create/update will fail. + LIST (1): + List operation. + GET (2): + Get operation. + CREATE (3): + Create operation. + UPDATE (4): + Update operation. + DELETE (5): + Delete operation. + """ + + OPERATION_TYPE_UNSPECIFIED = 0 + LIST = 1 + GET = 2 + CREATE = 3 + UPDATE = 4 + DELETE = 5 + + entity_id: str = proto.Field( + proto.STRING, + number=1, + ) + operation: "Action.EntityOperation.OperationType" = proto.Field( + proto.ENUM, + number=2, + enum="Action.EntityOperation.OperationType", + ) + + connection_action_id: str = proto.Field( + proto.STRING, + number=4, + oneof="action_spec", + ) + entity_operation: EntityOperation = proto.Field( + proto.MESSAGE, + number=5, + oneof="action_spec", + message=EntityOperation, + ) + input_fields: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + output_fields: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class ConnectorTool(proto.Message): + r"""A ConnectorTool allows connections to different integrations. + See: + https://cloud.google.com/integration-connectors/docs/overview. + + Attributes: + connection (str): + Required. The full resource name of the referenced + Integration Connectors Connection. Format: + ``projects/{project}/locations/{location}/connections/{connection}`` + action (google.cloud.ces_v1beta.types.Action): + Required. Action for the tool to use. + auth_config (google.cloud.ces_v1beta.types.EndUserAuthConfig): + Optional. Configures how authentication is handled in + Integration Connectors. By default, an admin authentication + is passed in the Integration Connectors API requests. You + can override it with a different end-user authentication + config. **Note**: The Connection must have authentication + override enabled in order to specify an EUC configuration + here - otherwise, the ConnectorTool creation will fail. See + https://cloud.google.com/application-integration/docs/configure-connectors-task#configure-authentication-override + for details. + name (str): + Optional. The name of the tool that can be + used by the Agent to decide whether to call this + ConnectorTool. + description (str): + Optional. The description of the tool that + can be used by the Agent to decide whether to + call this ConnectorTool. + """ + + connection: str = proto.Field( + proto.STRING, + number=1, + ) + action: "Action" = proto.Field( + proto.MESSAGE, + number=2, + message="Action", + ) + auth_config: auth.EndUserAuthConfig = proto.Field( + proto.MESSAGE, + number=3, + message=auth.EndUserAuthConfig, + ) + name: str = proto.Field( + proto.STRING, + number=4, + ) + description: str = proto.Field( + proto.STRING, + number=5, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/connector_toolset.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/connector_toolset.py new file mode 100644 index 000000000000..49ae57eab687 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/connector_toolset.py @@ -0,0 +1,71 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.ces_v1beta.types import auth, connector_tool + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "ConnectorToolset", + }, +) + + +class ConnectorToolset(proto.Message): + r"""A toolset that generates tools from an Integration Connectors + Connection. + + Attributes: + connection (str): + Required. The full resource name of the referenced + Integration Connectors Connection. Format: + ``projects/{project}/locations/{location}/connections/{connection}`` + auth_config (google.cloud.ces_v1beta.types.EndUserAuthConfig): + Optional. Configures how authentication is handled in + Integration Connectors. By default, an admin authentication + is passed in the Integration Connectors API requests. You + can override it with a different end-user authentication + config. **Note**: The Connection must have authentication + override enabled in order to specify an EUC configuration + here - otherwise, the Toolset creation will fail. See: + https://cloud.google.com/application-integration/docs/configure-connectors-task#configure-authentication-override + connector_actions (MutableSequence[google.cloud.ces_v1beta.types.Action]): + Required. The list of connector + actions/entity operations to generate tools for. + """ + + connection: str = proto.Field( + proto.STRING, + number=1, + ) + auth_config: auth.EndUserAuthConfig = proto.Field( + proto.MESSAGE, + number=2, + message=auth.EndUserAuthConfig, + ) + connector_actions: MutableSequence[connector_tool.Action] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=connector_tool.Action, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/conversation.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/conversation.py new file mode 100644 index 000000000000..2fed6c82ad0c --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/conversation.py @@ -0,0 +1,239 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.ces_v1beta.types import common, example + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "Conversation", + }, +) + + +class Conversation(proto.Message): + r"""A conversation represents an interaction between an end user + and the CES app. + + Attributes: + name (str): + Identifier. The unique identifier of the conversation. + Format: + ``projects/{project}/locations/{location}/apps/{app}/conversations/{conversation}`` + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the conversation + was created. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the conversation + was completed. + turns (MutableSequence[google.cloud.ces_v1beta.types.Conversation.Turn]): + Required. The turns in the conversation. + turn_count (int): + Output only. The number of turns in the + conversation. + channel_type (google.cloud.ces_v1beta.types.Conversation.ChannelType): + DEPRECATED. Please use + [input_types][google.cloud.ces.v1beta.Conversation.input_types] + instead. + source (google.cloud.ces_v1beta.types.Conversation.Source): + Output only. Indicate the source of the + conversation. + input_types (MutableSequence[google.cloud.ces_v1beta.types.Conversation.InputType]): + Output only. The input types of the + conversation. + entry_agent (str): + Output only. The agent that initially handles the + conversation. If not specified, the conversation is handled + by the root agent. Format: + ``projects/{project}/locations/{location}/apps/{app}/agents/{agent}`` + deployment (str): + Output only. The deployment of the app used for processing + the conversation. Format: + ``projects/{project}/locations/{location}/apps/{app}/deployments/{deployment}`` + app_version (str): + Output only. The version of the app used for processing the + conversation. Format: + ``projects/{project}/locations/{location}/apps/{app}/versions/{version}`` + language_code (str): + Output only. The language code of the + conversation. + messages (MutableSequence[google.cloud.ces_v1beta.types.Message]): + Deprecated. Use turns instead. + """ + + class ChannelType(proto.Enum): + r"""The channel type of the conversation. + + Values: + CHANNEL_TYPE_UNSPECIFIED (0): + Unspecified channel type. + TEXT (1): + The conversation only contains text messages + between the end user and the agent. + AUDIO (2): + The conversation contains audio messages + between the end user and the agent. + MULTIMODAL (3): + The conversation multi-modal messages (e.g. + image) between the end user and the agent. + """ + + CHANNEL_TYPE_UNSPECIFIED = 0 + TEXT = 1 + AUDIO = 2 + MULTIMODAL = 3 + + class Source(proto.Enum): + r"""The source of the conversation. + + Values: + SOURCE_UNSPECIFIED (0): + Unspecified source. + LIVE (1): + The conversation is from the live end user. + SIMULATOR (2): + The conversation is from the simulator. + EVAL (3): + The conversation is from the evaluation. + """ + + SOURCE_UNSPECIFIED = 0 + LIVE = 1 + SIMULATOR = 2 + EVAL = 3 + + class InputType(proto.Enum): + r"""Type of the input message. + + Values: + INPUT_TYPE_UNSPECIFIED (0): + Unspecified input type. + INPUT_TYPE_TEXT (1): + The input message is text. + INPUT_TYPE_AUDIO (2): + The input message is audio. + INPUT_TYPE_IMAGE (3): + The input message is image. + INPUT_TYPE_BLOB (4): + The input message is blob file. + INPUT_TYPE_TOOL_RESPONSE (5): + The input message is client function tool + response. + INPUT_TYPE_VARIABLES (6): + The input message are variables. + """ + + INPUT_TYPE_UNSPECIFIED = 0 + INPUT_TYPE_TEXT = 1 + INPUT_TYPE_AUDIO = 2 + INPUT_TYPE_IMAGE = 3 + INPUT_TYPE_BLOB = 4 + INPUT_TYPE_TOOL_RESPONSE = 5 + INPUT_TYPE_VARIABLES = 6 + + class Turn(proto.Message): + r"""All information about a single turn in the conversation. + + Attributes: + messages (MutableSequence[google.cloud.ces_v1beta.types.Message]): + Optional. List of messages in the + conversation turn, including user input, agent + responses and intermediate events during the + processing. + root_span (google.cloud.ces_v1beta.types.Span): + Optional. The root span of the action + processing. + """ + + messages: MutableSequence[example.Message] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=example.Message, + ) + root_span: common.Span = proto.Field( + proto.MESSAGE, + number=2, + message=common.Span, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + turns: MutableSequence[Turn] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=Turn, + ) + turn_count: int = proto.Field( + proto.INT32, + number=7, + ) + channel_type: ChannelType = proto.Field( + proto.ENUM, + number=8, + enum=ChannelType, + ) + source: Source = proto.Field( + proto.ENUM, + number=9, + enum=Source, + ) + input_types: MutableSequence[InputType] = proto.RepeatedField( + proto.ENUM, + number=10, + enum=InputType, + ) + entry_agent: str = proto.Field( + proto.STRING, + number=11, + ) + deployment: str = proto.Field( + proto.STRING, + number=12, + ) + app_version: str = proto.Field( + proto.STRING, + number=13, + ) + language_code: str = proto.Field( + proto.STRING, + number=14, + ) + messages: MutableSequence[example.Message] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=example.Message, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/data_store.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/data_store.py new file mode 100644 index 000000000000..8c93f89c1012 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/data_store.py @@ -0,0 +1,158 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "DataStore", + }, +) + + +class DataStore(proto.Message): + r"""A DataStore resource in Vertex AI Search. + + Attributes: + name (str): + Required. Full resource name of the DataStore. Format: + ``projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}`` + type_ (google.cloud.ces_v1beta.types.DataStore.DataStoreType): + Output only. The type of the data store. This + field is readonly and populated by the server. + document_processing_mode (google.cloud.ces_v1beta.types.DataStore.DocumentProcessingMode): + Output only. The document processing mode for the data store + connection. Only set for PUBLIC_WEB and UNSTRUCTURED data + stores. + display_name (str): + Output only. The display name of the data + store. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the data store + was created. + connector_config (google.cloud.ces_v1beta.types.DataStore.ConnectorConfig): + Output only. The connector config for the + data store connection. + """ + + class DataStoreType(proto.Enum): + r"""The type of the data store. + + Values: + DATA_STORE_TYPE_UNSPECIFIED (0): + Not specified. This value indicates that the + data store type is not specified, so it will not + be used during search. + PUBLIC_WEB (1): + A data store that contains public web + content. + UNSTRUCTURED (2): + A data store that contains unstructured + private data. + FAQ (3): + A data store that contains structured data + used as FAQ. + CONNECTOR (4): + A data store that is a connector to a + first-party or a third-party service. + """ + + DATA_STORE_TYPE_UNSPECIFIED = 0 + PUBLIC_WEB = 1 + UNSTRUCTURED = 2 + FAQ = 3 + CONNECTOR = 4 + + class DocumentProcessingMode(proto.Enum): + r"""The document processing mode of the data store. + + Values: + DOCUMENT_PROCESSING_MODE_UNSPECIFIED (0): + Not specified. + DOCUMENTS (1): + Documents are processed as documents. + CHUNKS (2): + Documents are converted to chunks. + """ + + DOCUMENT_PROCESSING_MODE_UNSPECIFIED = 0 + DOCUMENTS = 1 + CHUNKS = 2 + + class ConnectorConfig(proto.Message): + r"""The connector config for the data store connection. + + Attributes: + collection (str): + Resource name of the collection the data + store belongs to. + collection_display_name (str): + Display name of the collection the data store + belongs to. + data_source (str): + The name of the data source. Example: ``salesforce``, + ``jira``, ``confluence``, ``bigquery``. + """ + + collection: str = proto.Field( + proto.STRING, + number=1, + ) + collection_display_name: str = proto.Field( + proto.STRING, + number=2, + ) + data_source: str = proto.Field( + proto.STRING, + number=3, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + type_: DataStoreType = proto.Field( + proto.ENUM, + number=2, + enum=DataStoreType, + ) + document_processing_mode: DocumentProcessingMode = proto.Field( + proto.ENUM, + number=4, + enum=DocumentProcessingMode, + ) + display_name: str = proto.Field( + proto.STRING, + number=5, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + connector_config: ConnectorConfig = proto.Field( + proto.MESSAGE, + number=7, + message=ConnectorConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/data_store_tool.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/data_store_tool.py new file mode 100644 index 000000000000..d9165f17ee7f --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/data_store_tool.py @@ -0,0 +1,527 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.ces_v1beta.types import common +from google.cloud.ces_v1beta.types import data_store as gcc_data_store + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "DataStoreTool", + }, +) + + +class DataStoreTool(proto.Message): + r"""Tool to retrieve from Vertex AI Search datastore or engine + for grounding. Accepts either a datastore or an engine, but not + both. See Vertex AI Search: + + https://cloud.google.com/generative-ai-app-builder/docs/enterprise-search-introduction. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + data_store_source (google.cloud.ces_v1beta.types.DataStoreTool.DataStoreSource): + Optional. Search within a single specific + DataStore. + + This field is a member of `oneof`_ ``search_source``. + engine_source (google.cloud.ces_v1beta.types.DataStoreTool.EngineSource): + Optional. Search within an Engine + (potentially across multiple DataStores). + + This field is a member of `oneof`_ ``search_source``. + name (str): + Required. The data store tool name. + description (str): + Optional. The tool description. + boost_specs (MutableSequence[google.cloud.ces_v1beta.types.DataStoreTool.BoostSpecs]): + Optional. Boost specification to boost + certain documents. + modality_configs (MutableSequence[google.cloud.ces_v1beta.types.DataStoreTool.ModalityConfig]): + Optional. The modality configs for the data + store. + filter_parameter_behavior (google.cloud.ces_v1beta.types.DataStoreTool.FilterParameterBehavior): + Optional. The filter parameter behavior. + """ + + class FilterParameterBehavior(proto.Enum): + r"""Filter parameter behavior. + + Values: + FILTER_PARAMETER_BEHAVIOR_UNSPECIFIED (0): + Default filter behavior. + Include filter parameter for connector + datastores. For the rest of the datastore types, + the filter input parameter is omitted. + ALWAYS_INCLUDE (2): + Always include filter parameter for all + datastore types. + NEVER_INCLUDE (3): + The filter parameter is never included in the + list of tool parameters, regardless of the + datastore type. + """ + + FILTER_PARAMETER_BEHAVIOR_UNSPECIFIED = 0 + ALWAYS_INCLUDE = 2 + NEVER_INCLUDE = 3 + + class RewriterConfig(proto.Message): + r"""Rewriter configuration. + + Attributes: + model_settings (google.cloud.ces_v1beta.types.ModelSettings): + Required. Configurations for the LLM model. + prompt (str): + Optional. The prompt definition. If not set, + default prompt will be used. + disabled (bool): + Optional. Whether the rewriter is disabled. + """ + + model_settings: common.ModelSettings = proto.Field( + proto.MESSAGE, + number=1, + message=common.ModelSettings, + ) + prompt: str = proto.Field( + proto.STRING, + number=2, + ) + disabled: bool = proto.Field( + proto.BOOL, + number=3, + ) + + class SummarizationConfig(proto.Message): + r"""Summarization configuration. + + Attributes: + model_settings (google.cloud.ces_v1beta.types.ModelSettings): + Optional. Configurations for the LLM model. + prompt (str): + Optional. The prompt definition. If not set, + default prompt will be used. + disabled (bool): + Optional. Whether summarization is disabled. + """ + + model_settings: common.ModelSettings = proto.Field( + proto.MESSAGE, + number=1, + message=common.ModelSettings, + ) + prompt: str = proto.Field( + proto.STRING, + number=2, + ) + disabled: bool = proto.Field( + proto.BOOL, + number=3, + ) + + class GroundingConfig(proto.Message): + r"""Grounding configuration. + + Attributes: + grounding_level (float): + Optional. The groundedness threshold of the answer based on + the retrieved sources. The value has a configurable range of + [1, 5]. The level is used to threshold the groundedness of + the answer, meaning that all responses with a groundedness + score below the threshold will fall back to returning + relevant snippets only. + + For example, a level of 3 means that the groundedness score + must be 3 or higher for the response to be returned. + disabled (bool): + Optional. Whether grounding is disabled. + """ + + grounding_level: float = proto.Field( + proto.FLOAT, + number=1, + ) + disabled: bool = proto.Field( + proto.BOOL, + number=2, + ) + + class DataStoreSource(proto.Message): + r"""Configuration for searching within a specific DataStore. + + Attributes: + filter (str): + Optional. Filter specification for the + DataStore. See: + + https://cloud.google.com/generative-ai-app-builder/docs/filter-search-metadata + data_store (google.cloud.ces_v1beta.types.DataStore): + Optional. The data store. + """ + + filter: str = proto.Field( + proto.STRING, + number=2, + ) + data_store: gcc_data_store.DataStore = proto.Field( + proto.MESSAGE, + number=4, + message=gcc_data_store.DataStore, + ) + + class EngineSource(proto.Message): + r"""Configuration for searching within an Engine, potentially + targeting specific DataStores. + + Attributes: + engine (str): + Required. Full resource name of the Engine. Format: + ``projects/{project}/locations/{location}/collections/{collection}/engines/{engine}`` + data_store_sources (MutableSequence[google.cloud.ces_v1beta.types.DataStoreTool.DataStoreSource]): + Optional. Use to target specific DataStores + within the Engine. If empty, the search applies + to all DataStores associated with the Engine. + filter (str): + Optional. A filter applied to the search across the Engine. + Not relevant and not used if 'data_store_sources' is + provided. See: + https://cloud.google.com/generative-ai-app-builder/docs/filter-search-metadata + """ + + engine: str = proto.Field( + proto.STRING, + number=1, + ) + data_store_sources: MutableSequence["DataStoreTool.DataStoreSource"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=2, + message="DataStoreTool.DataStoreSource", + ) + ) + filter: str = proto.Field( + proto.STRING, + number=3, + ) + + class BoostSpecs(proto.Message): + r"""Boost specifications to boost certain documents. + For more information, please refer to + https://cloud.google.com/generative-ai-app-builder/docs/boosting. + + Attributes: + data_stores (MutableSequence[str]): + Required. The Data Store where the boosting + configuration is applied. Full resource name of + DataStore, such as + projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}. + spec (MutableSequence[google.cloud.ces_v1beta.types.DataStoreTool.BoostSpec]): + Required. A list of boosting specifications. + """ + + data_stores: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + spec: MutableSequence["DataStoreTool.BoostSpec"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="DataStoreTool.BoostSpec", + ) + + class BoostSpec(proto.Message): + r"""Boost specification to boost certain documents. + + Attributes: + condition_boost_specs (MutableSequence[google.cloud.ces_v1beta.types.DataStoreTool.BoostSpec.ConditionBoostSpec]): + Required. A list of boosting specifications. + """ + + class ConditionBoostSpec(proto.Message): + r"""Boost specification for a condition. + + Attributes: + condition (str): + Required. An expression which specifies a boost condition. + The syntax is the same as filter expression syntax. + Currently, the only supported condition is a list of BCP-47 + lang codes. Example: To boost suggestions in languages en or + fr: (lang_code: ANY("en", "fr")) + boost (float): + Optional. Strength of the boost, which should be in [-1, 1]. + Negative boost means demotion. Default is 0.0. + + Setting to 1.0 gives the suggestions a big promotion. + However, it does not necessarily mean that the top result + will be a boosted suggestion. + + Setting to -1.0 gives the suggestions a big demotion. + However, other suggestions that are relevant might still be + shown. + + Setting to 0.0 means no boost applied. The boosting + condition is ignored. + boost_control_spec (google.cloud.ces_v1beta.types.DataStoreTool.BoostSpec.ConditionBoostSpec.BoostControlSpec): + Optional. Complex specification for custom + ranking based on customer defined attribute + value. + """ + + class BoostControlSpec(proto.Message): + r"""Specification for custom ranking based on customer specified + attribute value. It provides more controls for customized + ranking than the simple (condition, boost) combination above. + + Attributes: + field_name (str): + Optional. The name of the field whose value + will be used to determine the boost amount. + attribute_type (google.cloud.ces_v1beta.types.DataStoreTool.BoostSpec.ConditionBoostSpec.BoostControlSpec.AttributeType): + Optional. The attribute type to be used to determine the + boost amount. The attribute value can be derived from the + field value of the specified field_name. In the case of + numerical it is straightforward i.e. attribute_value = + numerical_field_value. In the case of freshness however, + attribute_value = (time.now() - datetime_field_value). + interpolation_type (google.cloud.ces_v1beta.types.DataStoreTool.BoostSpec.ConditionBoostSpec.BoostControlSpec.InterpolationType): + Optional. The interpolation type to be + applied to connect the control points listed + below. + control_points (MutableSequence[google.cloud.ces_v1beta.types.DataStoreTool.BoostSpec.ConditionBoostSpec.BoostControlSpec.ControlPoint]): + Optional. The control points used to define the curve. The + monotonic function (defined through the interpolation_type + above) passes through the control points listed here. + """ + + class AttributeType(proto.Enum): + r"""The attribute(or function) for which the custom ranking is to + be applied. + + Values: + ATTRIBUTE_TYPE_UNSPECIFIED (0): + Unspecified AttributeType. + NUMERICAL (1): + The value of the numerical field will be used to dynamically + update the boost amount. In this case, the attribute_value + (the x value) of the control point will be the actual value + of the numerical field for which the boost_amount is + specified. + FRESHNESS (2): + For the freshness use case the attribute value will be the + duration between the current time and the date in the + datetime field specified. The value must be formatted as an + XSD ``dayTimeDuration`` value (a restricted subset of an ISO + 8601 duration value). The pattern for this is: + ``[nD][T[nH][nM][nS]]``. E.g. ``5D``, ``3DT12H30M``, + ``T24H``. + """ + + ATTRIBUTE_TYPE_UNSPECIFIED = 0 + NUMERICAL = 1 + FRESHNESS = 2 + + class InterpolationType(proto.Enum): + r"""The interpolation type to be applied. Default will be linear + (Piecewise Linear). + + Values: + INTERPOLATION_TYPE_UNSPECIFIED (0): + Interpolation type is unspecified. In this + case, it defaults to Linear. + LINEAR (1): + Piecewise linear interpolation will be + applied. + """ + + INTERPOLATION_TYPE_UNSPECIFIED = 0 + LINEAR = 1 + + class ControlPoint(proto.Message): + r"""The control points used to define the curve. The curve + defined through these control points can only be monotonically + increasing or decreasing(constant values are acceptable). + + Attributes: + attribute_value (str): + Optional. Can be one of: + + 1. The numerical field value. + 2. The duration spec for freshness: The value must be + formatted as an XSD ``dayTimeDuration`` value (a + restricted subset of an ISO 8601 duration value). The + pattern for this is: ``[nD][T[nH][nM][nS]]``. + boost_amount (float): + Optional. The value between -1 to 1 by which to boost the + score if the attribute_value evaluates to the value + specified above. + """ + + attribute_value: str = proto.Field( + proto.STRING, + number=1, + ) + boost_amount: float = proto.Field( + proto.FLOAT, + number=2, + ) + + field_name: str = proto.Field( + proto.STRING, + number=1, + ) + attribute_type: "DataStoreTool.BoostSpec.ConditionBoostSpec.BoostControlSpec.AttributeType" = proto.Field( + proto.ENUM, + number=2, + enum="DataStoreTool.BoostSpec.ConditionBoostSpec.BoostControlSpec.AttributeType", + ) + interpolation_type: "DataStoreTool.BoostSpec.ConditionBoostSpec.BoostControlSpec.InterpolationType" = proto.Field( + proto.ENUM, + number=3, + enum="DataStoreTool.BoostSpec.ConditionBoostSpec.BoostControlSpec.InterpolationType", + ) + control_points: MutableSequence[ + "DataStoreTool.BoostSpec.ConditionBoostSpec.BoostControlSpec.ControlPoint" + ] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message="DataStoreTool.BoostSpec.ConditionBoostSpec.BoostControlSpec.ControlPoint", + ) + + condition: str = proto.Field( + proto.STRING, + number=1, + ) + boost: float = proto.Field( + proto.FLOAT, + number=2, + ) + boost_control_spec: "DataStoreTool.BoostSpec.ConditionBoostSpec.BoostControlSpec" = proto.Field( + proto.MESSAGE, + number=4, + message="DataStoreTool.BoostSpec.ConditionBoostSpec.BoostControlSpec", + ) + + condition_boost_specs: MutableSequence[ + "DataStoreTool.BoostSpec.ConditionBoostSpec" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="DataStoreTool.BoostSpec.ConditionBoostSpec", + ) + + class ModalityConfig(proto.Message): + r"""If specified, will apply the given configuration for the + specified modality. + + Attributes: + modality_type (google.cloud.ces_v1beta.types.DataStoreTool.ModalityConfig.ModalityType): + Required. The modality type. + rewriter_config (google.cloud.ces_v1beta.types.DataStoreTool.RewriterConfig): + Optional. The rewriter config. + summarization_config (google.cloud.ces_v1beta.types.DataStoreTool.SummarizationConfig): + Optional. The summarization config. + grounding_config (google.cloud.ces_v1beta.types.DataStoreTool.GroundingConfig): + Optional. The grounding configuration. + """ + + class ModalityType(proto.Enum): + r"""The modality type. + + Values: + MODALITY_TYPE_UNSPECIFIED (0): + Unspecified modality type. + TEXT (1): + Text modality. + AUDIO (2): + Audio modality. + """ + + MODALITY_TYPE_UNSPECIFIED = 0 + TEXT = 1 + AUDIO = 2 + + modality_type: "DataStoreTool.ModalityConfig.ModalityType" = proto.Field( + proto.ENUM, + number=1, + enum="DataStoreTool.ModalityConfig.ModalityType", + ) + rewriter_config: "DataStoreTool.RewriterConfig" = proto.Field( + proto.MESSAGE, + number=2, + message="DataStoreTool.RewriterConfig", + ) + summarization_config: "DataStoreTool.SummarizationConfig" = proto.Field( + proto.MESSAGE, + number=3, + message="DataStoreTool.SummarizationConfig", + ) + grounding_config: "DataStoreTool.GroundingConfig" = proto.Field( + proto.MESSAGE, + number=4, + message="DataStoreTool.GroundingConfig", + ) + + data_store_source: DataStoreSource = proto.Field( + proto.MESSAGE, + number=3, + oneof="search_source", + message=DataStoreSource, + ) + engine_source: EngineSource = proto.Field( + proto.MESSAGE, + number=4, + oneof="search_source", + message=EngineSource, + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + boost_specs: MutableSequence[BoostSpecs] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=BoostSpecs, + ) + modality_configs: MutableSequence[ModalityConfig] = proto.RepeatedField( + proto.MESSAGE, + number=9, + message=ModalityConfig, + ) + filter_parameter_behavior: FilterParameterBehavior = proto.Field( + proto.ENUM, + number=10, + enum=FilterParameterBehavior, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/deployment.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/deployment.py new file mode 100644 index 000000000000..d07e706991f2 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/deployment.py @@ -0,0 +1,100 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.ces_v1beta.types import common + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "Deployment", + }, +) + + +class Deployment(proto.Message): + r"""A deployment represents an immutable, queryable version of + the app. It is used to deploy an app version with a specific + channel profile. + + Attributes: + name (str): + Identifier. The resource name of the deployment. Format: + ``projects/{project}/locations/{location}/apps/{app}/deployments/{deployment}`` + display_name (str): + Required. Display name of the deployment. + app_version (str): + Optional. The resource name of the app version to deploy. + Format: + ``projects/{project}/locations/{location}/apps/{app}/versions/{version}`` + Use + ``projects/{project}/locations/{location}/apps/{app}/versions/-`` + to use the draft app. + channel_profile (google.cloud.ces_v1beta.types.ChannelProfile): + Required. The channel profile used in the + deployment. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when this deployment + was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when this deployment + was last updated. + etag (str): + Output only. Etag used to ensure the object + hasn't changed during a read-modify-write + operation. If the etag is empty, the update will + overwrite any concurrent changes. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=8, + ) + app_version: str = proto.Field( + proto.STRING, + number=2, + ) + channel_profile: common.ChannelProfile = proto.Field( + proto.MESSAGE, + number=3, + message=common.ChannelProfile, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + etag: str = proto.Field( + proto.STRING, + number=7, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/evaluation.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/evaluation.py new file mode 100644 index 000000000000..30d0a3f2876d --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/evaluation.py @@ -0,0 +1,3142 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.struct_pb2 as struct_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.ces_v1beta.types import app as gcc_app +from google.cloud.ces_v1beta.types import ( + common, + example, + fakes, + golden_run, + session_service, +) +from google.cloud.ces_v1beta.types import toolset_tool as gcc_toolset_tool + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "AggregatedMetrics", + "Evaluation", + "EvaluationDataset", + "EvaluationResult", + "EvaluationRun", + "LatencyReport", + "EvaluationExpectation", + "EvaluationConfig", + "EvaluationErrorInfo", + "RunEvaluationRequest", + "ScheduledEvaluationRun", + "PersonaRunConfig", + "OptimizationConfig", + }, +) + + +class AggregatedMetrics(proto.Message): + r"""Aggregated metrics for an evaluation or evaluation dataset. + + Attributes: + metrics_by_app_version (MutableSequence[google.cloud.ces_v1beta.types.AggregatedMetrics.MetricsByAppVersion]): + Output only. Aggregated metrics, grouped by + app version ID. + """ + + class ToolMetrics(proto.Message): + r"""Metrics for a single tool. + + Attributes: + tool (str): + Output only. The name of the tool. + pass_count (int): + Output only. The number of times the tool + passed. + fail_count (int): + Output only. The number of times the tool + failed. + """ + + tool: str = proto.Field( + proto.STRING, + number=1, + ) + pass_count: int = proto.Field( + proto.INT32, + number=2, + ) + fail_count: int = proto.Field( + proto.INT32, + number=3, + ) + + class TurnLatencyMetrics(proto.Message): + r"""Metrics for turn latency. + + Attributes: + average_latency (google.protobuf.duration_pb2.Duration): + Output only. The average latency of the + turns. + """ + + average_latency: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + + class ToolCallLatencyMetrics(proto.Message): + r"""Metrics for tool call latency. + + Attributes: + tool (str): + Output only. The name of the tool. + average_latency (google.protobuf.duration_pb2.Duration): + Output only. The average latency of the tool + calls. + """ + + tool: str = proto.Field( + proto.STRING, + number=1, + ) + average_latency: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + class SemanticSimilarityMetrics(proto.Message): + r"""Metrics for semantic similarity results. + + Attributes: + score (float): + Output only. The average semantic similarity + score (0-4). + """ + + score: float = proto.Field( + proto.FLOAT, + number=1, + ) + + class HallucinationMetrics(proto.Message): + r"""Metrics for hallucination results. + + Attributes: + score (float): + Output only. The average hallucination score + (0 to 1). + """ + + score: float = proto.Field( + proto.FLOAT, + number=1, + ) + + class MetricsByAppVersion(proto.Message): + r"""Metrics aggregated per app version. + + Attributes: + app_version_id (str): + Output only. The app version ID. + tool_metrics (MutableSequence[google.cloud.ces_v1beta.types.AggregatedMetrics.ToolMetrics]): + Output only. Metrics for each tool within + this app version. + semantic_similarity_metrics (MutableSequence[google.cloud.ces_v1beta.types.AggregatedMetrics.SemanticSimilarityMetrics]): + Output only. Metrics for semantic similarity + within this app version. + hallucination_metrics (MutableSequence[google.cloud.ces_v1beta.types.AggregatedMetrics.HallucinationMetrics]): + Output only. Metrics for hallucination within + this app version. + tool_call_latency_metrics (MutableSequence[google.cloud.ces_v1beta.types.AggregatedMetrics.ToolCallLatencyMetrics]): + Output only. Metrics for tool call latency + within this app version. + turn_latency_metrics (MutableSequence[google.cloud.ces_v1beta.types.AggregatedMetrics.TurnLatencyMetrics]): + Output only. Metrics for turn latency within + this app version. + pass_count (int): + Output only. The number of times the + evaluation passed. + fail_count (int): + Output only. The number of times the + evaluation failed. + metrics_by_turn (MutableSequence[google.cloud.ces_v1beta.types.AggregatedMetrics.MetricsByTurn]): + Output only. Metrics aggregated per turn + within this app version. + """ + + app_version_id: str = proto.Field( + proto.STRING, + number=1, + ) + tool_metrics: MutableSequence["AggregatedMetrics.ToolMetrics"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=2, + message="AggregatedMetrics.ToolMetrics", + ) + ) + semantic_similarity_metrics: MutableSequence[ + "AggregatedMetrics.SemanticSimilarityMetrics" + ] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="AggregatedMetrics.SemanticSimilarityMetrics", + ) + hallucination_metrics: MutableSequence[ + "AggregatedMetrics.HallucinationMetrics" + ] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message="AggregatedMetrics.HallucinationMetrics", + ) + tool_call_latency_metrics: MutableSequence[ + "AggregatedMetrics.ToolCallLatencyMetrics" + ] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message="AggregatedMetrics.ToolCallLatencyMetrics", + ) + turn_latency_metrics: MutableSequence[ + "AggregatedMetrics.TurnLatencyMetrics" + ] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message="AggregatedMetrics.TurnLatencyMetrics", + ) + pass_count: int = proto.Field( + proto.INT32, + number=8, + ) + fail_count: int = proto.Field( + proto.INT32, + number=9, + ) + metrics_by_turn: MutableSequence["AggregatedMetrics.MetricsByTurn"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=4, + message="AggregatedMetrics.MetricsByTurn", + ) + ) + + class MetricsByTurn(proto.Message): + r"""Metrics aggregated per turn. + + Attributes: + turn_index (int): + Output only. The turn index (0-based). + tool_metrics (MutableSequence[google.cloud.ces_v1beta.types.AggregatedMetrics.ToolMetrics]): + Output only. Metrics for each tool within + this turn. + semantic_similarity_metrics (MutableSequence[google.cloud.ces_v1beta.types.AggregatedMetrics.SemanticSimilarityMetrics]): + Output only. Metrics for semantic similarity + within this turn. + hallucination_metrics (MutableSequence[google.cloud.ces_v1beta.types.AggregatedMetrics.HallucinationMetrics]): + Output only. Metrics for hallucination within + this turn. + tool_call_latency_metrics (MutableSequence[google.cloud.ces_v1beta.types.AggregatedMetrics.ToolCallLatencyMetrics]): + Output only. Metrics for tool call latency + within this turn. + turn_latency_metrics (MutableSequence[google.cloud.ces_v1beta.types.AggregatedMetrics.TurnLatencyMetrics]): + Output only. Metrics for turn latency within + this turn. + """ + + turn_index: int = proto.Field( + proto.INT32, + number=1, + ) + tool_metrics: MutableSequence["AggregatedMetrics.ToolMetrics"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=2, + message="AggregatedMetrics.ToolMetrics", + ) + ) + semantic_similarity_metrics: MutableSequence[ + "AggregatedMetrics.SemanticSimilarityMetrics" + ] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="AggregatedMetrics.SemanticSimilarityMetrics", + ) + hallucination_metrics: MutableSequence[ + "AggregatedMetrics.HallucinationMetrics" + ] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message="AggregatedMetrics.HallucinationMetrics", + ) + tool_call_latency_metrics: MutableSequence[ + "AggregatedMetrics.ToolCallLatencyMetrics" + ] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message="AggregatedMetrics.ToolCallLatencyMetrics", + ) + turn_latency_metrics: MutableSequence[ + "AggregatedMetrics.TurnLatencyMetrics" + ] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message="AggregatedMetrics.TurnLatencyMetrics", + ) + + metrics_by_app_version: MutableSequence[MetricsByAppVersion] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=MetricsByAppVersion, + ) + + +class Evaluation(proto.Message): + r"""An evaluation represents all of the information needed to + simulate and evaluate an agent. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + golden (google.cloud.ces_v1beta.types.Evaluation.Golden): + Optional. The golden steps to be evaluated. + + This field is a member of `oneof`_ ``inputs``. + scenario (google.cloud.ces_v1beta.types.Evaluation.Scenario): + Optional. The config for a scenario. + + This field is a member of `oneof`_ ``inputs``. + name (str): + Identifier. The unique identifier of this evaluation. + Format: + ``projects/{project}/locations/{location}/apps/{app}/evaluations/{evaluation}`` + display_name (str): + Required. User-defined display name of the + evaluation. Unique within an App. + description (str): + Optional. User-defined description of the + evaluation. + tags (MutableSequence[str]): + Optional. User defined tags to categorize the + evaluation. + evaluation_datasets (MutableSequence[str]): + Output only. List of evaluation datasets the evaluation + belongs to. Format: + ``projects/{project}/locations/{location}/apps/{app}/evaluationDatasets/{evaluationDataset}`` + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the evaluation + was created. + created_by (str): + Output only. The user who created the + evaluation. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the evaluation + was last updated. + last_updated_by (str): + Output only. The user who last updated the + evaluation. + evaluation_runs (MutableSequence[str]): + Output only. The EvaluationRuns that this + Evaluation is associated with. + etag (str): + Output only. Etag used to ensure the object + hasn't changed during a read-modify-write + operation. If the etag is empty, the update will + overwrite any concurrent changes. + aggregated_metrics (google.cloud.ces_v1beta.types.AggregatedMetrics): + Output only. The aggregated metrics for this + evaluation across all runs. + last_completed_result (google.cloud.ces_v1beta.types.EvaluationResult): + Output only. The latest evaluation result for + this evaluation. + invalid (bool): + Output only. Whether the evaluation is + invalid. This can happen if an evaluation is + referencing a tool, toolset, or agent that has + since been deleted. + last_ten_results (MutableSequence[google.cloud.ces_v1beta.types.EvaluationResult]): + Output only. The last 10 evaluation results for this + evaluation. This is only populated if + include_last_ten_results is set to true in the + ListEvaluationsRequest or GetEvaluationRequest. + """ + + class GoldenExpectation(proto.Message): + r"""Represents a single, checkable requirement. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + tool_call (google.cloud.ces_v1beta.types.ToolCall): + Optional. Check that a specific tool was + called with the parameters. + + This field is a member of `oneof`_ ``condition``. + tool_response (google.cloud.ces_v1beta.types.ToolResponse): + Optional. Check that a specific tool had the + expected response. + + This field is a member of `oneof`_ ``condition``. + agent_response (google.cloud.ces_v1beta.types.Message): + Optional. Check that the agent responded with + the correct response. The role "agent" is + implied. + + This field is a member of `oneof`_ ``condition``. + agent_transfer (google.cloud.ces_v1beta.types.AgentTransfer): + Optional. Check that the agent transferred + the conversation to a different agent. + + This field is a member of `oneof`_ ``condition``. + updated_variables (google.protobuf.struct_pb2.Struct): + Optional. Check that the agent updated the + session variables to the expected values. Used + to also capture agent variable updates for + golden evals. + + This field is a member of `oneof`_ ``condition``. + mock_tool_response (google.cloud.ces_v1beta.types.ToolResponse): + Optional. The tool response to mock, with the + parameters of interest specified. Any parameters + not specified will be hallucinated by the LLM. + + This field is a member of `oneof`_ ``condition``. + note (str): + Optional. A note for this requirement, useful in reporting + when specific checks fail. E.g., + "Check_Payment_Tool_Called". + """ + + tool_call: example.ToolCall = proto.Field( + proto.MESSAGE, + number=2, + oneof="condition", + message=example.ToolCall, + ) + tool_response: example.ToolResponse = proto.Field( + proto.MESSAGE, + number=3, + oneof="condition", + message=example.ToolResponse, + ) + agent_response: example.Message = proto.Field( + proto.MESSAGE, + number=4, + oneof="condition", + message=example.Message, + ) + agent_transfer: example.AgentTransfer = proto.Field( + proto.MESSAGE, + number=5, + oneof="condition", + message=example.AgentTransfer, + ) + updated_variables: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=6, + oneof="condition", + message=struct_pb2.Struct, + ) + mock_tool_response: example.ToolResponse = proto.Field( + proto.MESSAGE, + number=7, + oneof="condition", + message=example.ToolResponse, + ) + note: str = proto.Field( + proto.STRING, + number=1, + ) + + class Step(proto.Message): + r"""A step defines a singular action to happen during the + evaluation. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + user_input (google.cloud.ces_v1beta.types.SessionInput): + Optional. User input for the conversation. + + This field is a member of `oneof`_ ``step``. + agent_transfer (google.cloud.ces_v1beta.types.AgentTransfer): + Optional. Transfer the conversation to a + different agent. + + This field is a member of `oneof`_ ``step``. + expectation (google.cloud.ces_v1beta.types.Evaluation.GoldenExpectation): + Optional. Executes an expectation on the + current turn. + + This field is a member of `oneof`_ ``step``. + """ + + user_input: session_service.SessionInput = proto.Field( + proto.MESSAGE, + number=1, + oneof="step", + message=session_service.SessionInput, + ) + agent_transfer: example.AgentTransfer = proto.Field( + proto.MESSAGE, + number=2, + oneof="step", + message=example.AgentTransfer, + ) + expectation: "Evaluation.GoldenExpectation" = proto.Field( + proto.MESSAGE, + number=3, + oneof="step", + message="Evaluation.GoldenExpectation", + ) + + class GoldenTurn(proto.Message): + r"""A golden turn defines a single turn in a golden conversation. + + Attributes: + steps (MutableSequence[google.cloud.ces_v1beta.types.Evaluation.Step]): + Required. The steps required to replay a + golden conversation. + root_span (google.cloud.ces_v1beta.types.Span): + Optional. The root span of the golden turn + for processing and maintaining audio + information. + """ + + steps: MutableSequence["Evaluation.Step"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Evaluation.Step", + ) + root_span: common.Span = proto.Field( + proto.MESSAGE, + number=2, + message=common.Span, + ) + + class Golden(proto.Message): + r"""The steps required to replay a golden conversation. + + Attributes: + turns (MutableSequence[google.cloud.ces_v1beta.types.Evaluation.GoldenTurn]): + Required. The golden turns required to replay + a golden conversation. + evaluation_expectations (MutableSequence[str]): + Optional. The evaluation expectations to evaluate the + replayed conversation against. Format: + ``projects/{project}/locations/{location}/apps/{app}/evaluationExpectations/{evaluationExpectation}`` + """ + + turns: MutableSequence["Evaluation.GoldenTurn"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="Evaluation.GoldenTurn", + ) + evaluation_expectations: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + class ScenarioExpectation(proto.Message): + r"""The expectation to evaluate the conversation produced by the + simulation. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + tool_expectation (google.cloud.ces_v1beta.types.Evaluation.ScenarioExpectation.ToolExpectation): + Optional. The tool call and response pair to + be evaluated. + + This field is a member of `oneof`_ ``expectation``. + agent_response (google.cloud.ces_v1beta.types.Message): + Optional. The agent response to be evaluated. + + This field is a member of `oneof`_ ``expectation``. + """ + + class ToolExpectation(proto.Message): + r"""The tool call and response pair to be evaluated. + + Attributes: + expected_tool_call (google.cloud.ces_v1beta.types.ToolCall): + Required. The expected tool call, with the + parameters of interest specified. Any parameters + not specified will be hallucinated by the LLM. + mock_tool_response (google.cloud.ces_v1beta.types.ToolResponse): + Required. The tool response to mock, with the + parameters of interest specified. Any parameters + not specified will be hallucinated by the LLM. + """ + + expected_tool_call: example.ToolCall = proto.Field( + proto.MESSAGE, + number=1, + message=example.ToolCall, + ) + mock_tool_response: example.ToolResponse = proto.Field( + proto.MESSAGE, + number=2, + message=example.ToolResponse, + ) + + tool_expectation: "Evaluation.ScenarioExpectation.ToolExpectation" = ( + proto.Field( + proto.MESSAGE, + number=1, + oneof="expectation", + message="Evaluation.ScenarioExpectation.ToolExpectation", + ) + ) + agent_response: example.Message = proto.Field( + proto.MESSAGE, + number=2, + oneof="expectation", + message=example.Message, + ) + + class Scenario(proto.Message): + r"""The config for a scenario + + Attributes: + task (str): + Required. The task to be targeted by the + scenario. + user_facts (MutableSequence[google.cloud.ces_v1beta.types.Evaluation.Scenario.UserFact]): + Optional. The user facts to be used by the + scenario. + max_turns (int): + Optional. The maximum number of turns to + simulate. If not specified, the simulation will + continue until the task is complete. + rubrics (MutableSequence[str]): + Required. The rubrics to score the scenario + against. + scenario_expectations (MutableSequence[google.cloud.ces_v1beta.types.Evaluation.ScenarioExpectation]): + Required. The ScenarioExpectations to + evaluate the conversation produced by the user + simulation. + variable_overrides (google.protobuf.struct_pb2.Struct): + Optional. Variables / Session Parameters as + context for the session, keyed by variable + names. Members of this struct will override any + default values set by the system. + + Note, these are different from user facts, which + are facts known to the user. Variables are + parameters known to the agent: i.e. MDN (phone + number) passed by the telephony system. + task_completion_behavior (google.cloud.ces_v1beta.types.Evaluation.Scenario.TaskCompletionBehavior): + Optional. Deprecated. Use user_goal_behavior instead. + user_goal_behavior (google.cloud.ces_v1beta.types.Evaluation.Scenario.UserGoalBehavior): + Optional. The expected behavior of the user + goal. + evaluation_expectations (MutableSequence[str]): + Optional. The evaluation expectations to evaluate the + conversation produced by the simulation against. Format: + ``projects/{project}/locations/{location}/apps/{app}/evaluationExpectations/{evaluationExpectation}`` + """ + + class TaskCompletionBehavior(proto.Enum): + r"""The expected behavior of the user task. This is used to + determine whether the scenario is successful. + + Values: + TASK_COMPLETION_BEHAVIOR_UNSPECIFIED (0): + Behavior unspecified. Will default to TASK_SATISFIED. + TASK_SATISFIED (1): + The user task should be completed + successfully. + TASK_REJECTED (2): + The user task should be rejected. + """ + + TASK_COMPLETION_BEHAVIOR_UNSPECIFIED = 0 + TASK_SATISFIED = 1 + TASK_REJECTED = 2 + + class UserGoalBehavior(proto.Enum): + r"""The expected behavior of the user goal. This is used to + determine whether the scenario is successful. + + Values: + USER_GOAL_BEHAVIOR_UNSPECIFIED (0): + Behavior unspecified. Will default to USER_GOAL_SATISFIED. + USER_GOAL_SATISFIED (1): + The user goal should be completed + successfully. + USER_GOAL_REJECTED (2): + The user goal should be rejected. + USER_GOAL_IGNORED (3): + Ignore the user goal status. + """ + + USER_GOAL_BEHAVIOR_UNSPECIFIED = 0 + USER_GOAL_SATISFIED = 1 + USER_GOAL_REJECTED = 2 + USER_GOAL_IGNORED = 3 + + class UserFact(proto.Message): + r"""Facts about the user as a key value pair. + + Attributes: + name (str): + Required. The name of the user fact. + value (str): + Required. The value of the user fact. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + value: str = proto.Field( + proto.STRING, + number=2, + ) + + task: str = proto.Field( + proto.STRING, + number=1, + ) + user_facts: MutableSequence["Evaluation.Scenario.UserFact"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=4, + message="Evaluation.Scenario.UserFact", + ) + ) + max_turns: int = proto.Field( + proto.INT32, + number=5, + ) + rubrics: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + scenario_expectations: MutableSequence["Evaluation.ScenarioExpectation"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=3, + message="Evaluation.ScenarioExpectation", + ) + ) + variable_overrides: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=6, + message=struct_pb2.Struct, + ) + task_completion_behavior: "Evaluation.Scenario.TaskCompletionBehavior" = ( + proto.Field( + proto.ENUM, + number=7, + enum="Evaluation.Scenario.TaskCompletionBehavior", + ) + ) + user_goal_behavior: "Evaluation.Scenario.UserGoalBehavior" = proto.Field( + proto.ENUM, + number=8, + enum="Evaluation.Scenario.UserGoalBehavior", + ) + evaluation_expectations: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=10, + ) + + golden: Golden = proto.Field( + proto.MESSAGE, + number=11, + oneof="inputs", + message=Golden, + ) + scenario: Scenario = proto.Field( + proto.MESSAGE, + number=12, + oneof="inputs", + message=Scenario, + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + tags: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + evaluation_datasets: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + created_by: str = proto.Field( + proto.STRING, + number=13, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + last_updated_by: str = proto.Field( + proto.STRING, + number=14, + ) + evaluation_runs: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=15, + ) + etag: str = proto.Field( + proto.STRING, + number=10, + ) + aggregated_metrics: "AggregatedMetrics" = proto.Field( + proto.MESSAGE, + number=16, + message="AggregatedMetrics", + ) + last_completed_result: "EvaluationResult" = proto.Field( + proto.MESSAGE, + number=17, + message="EvaluationResult", + ) + invalid: bool = proto.Field( + proto.BOOL, + number=18, + ) + last_ten_results: MutableSequence["EvaluationResult"] = proto.RepeatedField( + proto.MESSAGE, + number=19, + message="EvaluationResult", + ) + + +class EvaluationDataset(proto.Message): + r"""An evaluation dataset represents a set of evaluations that + are grouped together basaed on shared tags. + + Attributes: + name (str): + Identifier. The unique identifier of this evaluation + dataset. Format: + ``projects/{project}/locations/{location}/apps/{app}/evaluationDatasets/{evaluationDataset}`` + display_name (str): + Required. User-defined display name of the + evaluation dataset. Unique within an App. + evaluations (MutableSequence[str]): + Optional. Evaluations that are included in + this dataset. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the evaluation + dataset was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the evaluation + dataset was last updated. + etag (str): + Output only. Etag used to ensure the object + hasn't changed during a read-modify-write + operation. If the etag is empty, the update will + overwrite any concurrent changes. + created_by (str): + Output only. The user who created the + evaluation dataset. + last_updated_by (str): + Output only. The user who last updated the + evaluation dataset. + aggregated_metrics (google.cloud.ces_v1beta.types.AggregatedMetrics): + Output only. The aggregated metrics for this + evaluation dataset across all runs. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + evaluations: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + etag: str = proto.Field( + proto.STRING, + number=6, + ) + created_by: str = proto.Field( + proto.STRING, + number=7, + ) + last_updated_by: str = proto.Field( + proto.STRING, + number=8, + ) + aggregated_metrics: "AggregatedMetrics" = proto.Field( + proto.MESSAGE, + number=9, + message="AggregatedMetrics", + ) + + +class EvaluationResult(proto.Message): + r"""An evaluation result represents the output of running an + Evaluation. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + golden_result (google.cloud.ces_v1beta.types.EvaluationResult.GoldenResult): + Output only. The outcome of a golden + evaluation. + + This field is a member of `oneof`_ ``result``. + scenario_result (google.cloud.ces_v1beta.types.EvaluationResult.ScenarioResult): + Output only. The outcome of a scenario + evaluation. + + This field is a member of `oneof`_ ``result``. + name (str): + Identifier. The unique identifier of the evaluation result. + Format: + ``projects/{project}/locations/{location}/apps/{app}/evaluations/{evaluation}/results/{result}`` + display_name (str): + Required. Display name of the Evaluation + Result. Unique within an Evaluation. By default, + it has the following format: + + " result + - ". + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the evaluation + result was created. + evaluation_status (google.cloud.ces_v1beta.types.EvaluationResult.Outcome): + Output only. The outcome of the evaluation. Only populated + if execution_state is COMPLETE. + evaluation_run (str): + Output only. The evaluation run that produced this result. + Format: + ``projects/{project}/locations/{location}/apps/{app}/evaluationRuns/{evaluationRun}`` + persona (google.cloud.ces_v1beta.types.EvaluationPersona): + Output only. The persona used to generate the + conversation for the evaluation result. + error_info (google.cloud.ces_v1beta.types.EvaluationErrorInfo): + Output only. Error information for the + evaluation result. + error (google.rpc.status_pb2.Status): + Output only. Deprecated: Use ``error_info`` instead. Errors + encountered during execution. + initiated_by (str): + Output only. The user who initiated the + evaluation run that resulted in this result. + app_version (str): + Output only. The app version used to generate the + conversation that resulted in this result. Format: + ``projects/{project}/locations/{location}/apps/{app}/versions/{version}`` + app_version_display_name (str): + Output only. The display name of the ``app_version`` that + the evaluation ran against. + changelog (str): + Output only. The changelog of the app version + that the evaluation ran against. This is + populated if user runs evaluation on + latest/draft. + changelog_create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The create time of the changelog + of the app version that the evaluation ran + against. This is populated if user runs + evaluation on latest/draft. + execution_state (google.cloud.ces_v1beta.types.EvaluationResult.ExecutionState): + Output only. The state of the evaluation + result execution. + evaluation_metrics_thresholds (google.cloud.ces_v1beta.types.EvaluationMetricsThresholds): + Output only. The evaluation thresholds for + the result. + config (google.cloud.ces_v1beta.types.EvaluationConfig): + Output only. The configuration used in the + evaluation run that resulted in this result. + golden_run_method (google.cloud.ces_v1beta.types.GoldenRunMethod): + Output only. The method used to run the + golden evaluation. + """ + + class Outcome(proto.Enum): + r"""The outcome of the evaluation or expectation. + + Values: + OUTCOME_UNSPECIFIED (0): + Evaluation outcome is not specified. + PASS (1): + Evaluation/Expectation passed. In the case of + an evaluation, this means that all expectations + were met. + FAIL (2): + Evaluation/Expectation failed. In the case of + an evaluation, this means that at least one + expectation was not met. + """ + + OUTCOME_UNSPECIFIED = 0 + PASS = 1 + FAIL = 2 + + class ExecutionState(proto.Enum): + r"""The state of the evaluation result execution. + + Values: + EXECUTION_STATE_UNSPECIFIED (0): + Evaluation result execution state is not + specified. + RUNNING (1): + Evaluation result execution is running. + COMPLETED (2): + Evaluation result execution has completed. + ERROR (3): + Evaluation result execution failed due to an + internal error. + """ + + EXECUTION_STATE_UNSPECIFIED = 0 + RUNNING = 1 + COMPLETED = 2 + ERROR = 3 + + class GoldenExpectationOutcome(proto.Message): + r"""Specifies the expectation and the result of that expectation. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + observed_tool_call (google.cloud.ces_v1beta.types.ToolCall): + Output only. The result of the tool call + expectation. + + This field is a member of `oneof`_ ``result``. + observed_tool_response (google.cloud.ces_v1beta.types.ToolResponse): + Output only. The result of the tool response + expectation. + + This field is a member of `oneof`_ ``result``. + observed_agent_response (google.cloud.ces_v1beta.types.Message): + Output only. The result of the agent response + expectation. + + This field is a member of `oneof`_ ``result``. + observed_agent_transfer (google.cloud.ces_v1beta.types.AgentTransfer): + Output only. The result of the agent transfer + expectation. + + This field is a member of `oneof`_ ``result``. + expectation (google.cloud.ces_v1beta.types.Evaluation.GoldenExpectation): + Output only. The expectation that was + evaluated. + outcome (google.cloud.ces_v1beta.types.EvaluationResult.Outcome): + Output only. The outcome of the expectation. + semantic_similarity_result (google.cloud.ces_v1beta.types.EvaluationResult.SemanticSimilarityResult): + Output only. The result of the semantic + similarity check. + tool_invocation_result (google.cloud.ces_v1beta.types.EvaluationResult.GoldenExpectationOutcome.ToolInvocationResult): + Output only. The result of the tool + invocation check. + """ + + class ToolInvocationResult(proto.Message): + r"""The result of the tool invocation check. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parameter_correctness_score (float): + Output only. The tool invocation parameter + correctness score. This indicates the percent of + parameters from the expected tool call that were + also present in the actual tool call. + + This field is a member of `oneof`_ ``_parameter_correctness_score``. + outcome (google.cloud.ces_v1beta.types.EvaluationResult.Outcome): + Output only. The outcome of the tool invocation check. This + is determined by comparing the parameter_correctness_score + to the threshold. If the score is equal to or above the + threshold, the outcome will be PASS. Otherwise, the outcome + will be FAIL. + explanation (str): + Output only. A free text explanation for the + tool invocation result. + """ + + parameter_correctness_score: float = proto.Field( + proto.FLOAT, + number=1, + optional=True, + ) + outcome: "EvaluationResult.Outcome" = proto.Field( + proto.ENUM, + number=2, + enum="EvaluationResult.Outcome", + ) + explanation: str = proto.Field( + proto.STRING, + number=3, + ) + + observed_tool_call: example.ToolCall = proto.Field( + proto.MESSAGE, + number=2, + oneof="result", + message=example.ToolCall, + ) + observed_tool_response: example.ToolResponse = proto.Field( + proto.MESSAGE, + number=3, + oneof="result", + message=example.ToolResponse, + ) + observed_agent_response: example.Message = proto.Field( + proto.MESSAGE, + number=4, + oneof="result", + message=example.Message, + ) + observed_agent_transfer: example.AgentTransfer = proto.Field( + proto.MESSAGE, + number=5, + oneof="result", + message=example.AgentTransfer, + ) + expectation: "Evaluation.GoldenExpectation" = proto.Field( + proto.MESSAGE, + number=1, + message="Evaluation.GoldenExpectation", + ) + outcome: "EvaluationResult.Outcome" = proto.Field( + proto.ENUM, + number=6, + enum="EvaluationResult.Outcome", + ) + semantic_similarity_result: "EvaluationResult.SemanticSimilarityResult" = ( + proto.Field( + proto.MESSAGE, + number=7, + message="EvaluationResult.SemanticSimilarityResult", + ) + ) + tool_invocation_result: "EvaluationResult.GoldenExpectationOutcome.ToolInvocationResult" = proto.Field( + proto.MESSAGE, + number=8, + message="EvaluationResult.GoldenExpectationOutcome.ToolInvocationResult", + ) + + class EvaluationExpectationResult(proto.Message): + r"""The result of a single evaluation expectation. + + Attributes: + evaluation_expectation (str): + Output only. The evaluation expectation. Format: + ``projects/{project}/locations/{location}/apps/{app}/evaluationExpectations/{evaluation_expectation}`` + prompt (str): + Output only. The prompt that was used for the + evaluation. + outcome (google.cloud.ces_v1beta.types.EvaluationResult.Outcome): + Output only. The outcome of the evaluation + expectation. + explanation (str): + Output only. The explanation for the result. + """ + + evaluation_expectation: str = proto.Field( + proto.STRING, + number=1, + ) + prompt: str = proto.Field( + proto.STRING, + number=2, + ) + outcome: "EvaluationResult.Outcome" = proto.Field( + proto.ENUM, + number=3, + enum="EvaluationResult.Outcome", + ) + explanation: str = proto.Field( + proto.STRING, + number=4, + ) + + class GoldenResult(proto.Message): + r"""The result of a golden evaluation. + + Attributes: + turn_replay_results (MutableSequence[google.cloud.ces_v1beta.types.EvaluationResult.GoldenResult.TurnReplayResult]): + Output only. The result of running each turn + of the golden conversation. + evaluation_expectation_results (MutableSequence[google.cloud.ces_v1beta.types.EvaluationResult.EvaluationExpectationResult]): + Output only. The results of the evaluation + expectations. + """ + + class TurnReplayResult(proto.Message): + r"""The result of running a single turn of the golden + conversation. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + conversation (str): + Output only. The conversation that was + generated for this turn. + expectation_outcome (MutableSequence[google.cloud.ces_v1beta.types.EvaluationResult.GoldenExpectationOutcome]): + Output only. The outcome of each expectation. + hallucination_result (google.cloud.ces_v1beta.types.EvaluationResult.HallucinationResult): + Output only. The result of the hallucination + check. + tool_invocation_score (float): + Output only. Deprecated. Use + OverallToolInvocationResult instead. + tool_ordered_invocation_score (float): + Output only. The overall tool ordered + invocation score for this turn. This indicates + the overall percent of tools from the expected + turn that were actually invoked in the expected + order. + + This field is a member of `oneof`_ ``_tool_ordered_invocation_score``. + turn_latency (google.protobuf.duration_pb2.Duration): + Output only. Duration of the turn. + tool_call_latencies (MutableSequence[google.cloud.ces_v1beta.types.EvaluationResult.ToolCallLatency]): + Output only. The latency of each tool call in + the turn. + semantic_similarity_result (google.cloud.ces_v1beta.types.EvaluationResult.SemanticSimilarityResult): + Output only. The result of the semantic + similarity check. + overall_tool_invocation_result (google.cloud.ces_v1beta.types.EvaluationResult.OverallToolInvocationResult): + Output only. The result of the overall tool + invocation check. + error_info (google.cloud.ces_v1beta.types.EvaluationErrorInfo): + Output only. Information about the error that + occurred during this turn. + span_latencies (MutableSequence[google.cloud.ces_v1beta.types.EvaluationResult.SpanLatency]): + Output only. The latency of spans in the + turn. + """ + + conversation: str = proto.Field( + proto.STRING, + number=1, + ) + expectation_outcome: MutableSequence[ + "EvaluationResult.GoldenExpectationOutcome" + ] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="EvaluationResult.GoldenExpectationOutcome", + ) + hallucination_result: "EvaluationResult.HallucinationResult" = proto.Field( + proto.MESSAGE, + number=3, + message="EvaluationResult.HallucinationResult", + ) + tool_invocation_score: float = proto.Field( + proto.FLOAT, + number=4, + ) + tool_ordered_invocation_score: float = proto.Field( + proto.FLOAT, + number=5, + optional=True, + ) + turn_latency: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, + ) + tool_call_latencies: MutableSequence["EvaluationResult.ToolCallLatency"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=7, + message="EvaluationResult.ToolCallLatency", + ) + ) + semantic_similarity_result: "EvaluationResult.SemanticSimilarityResult" = ( + proto.Field( + proto.MESSAGE, + number=8, + message="EvaluationResult.SemanticSimilarityResult", + ) + ) + overall_tool_invocation_result: "EvaluationResult.OverallToolInvocationResult" = proto.Field( + proto.MESSAGE, + number=9, + message="EvaluationResult.OverallToolInvocationResult", + ) + error_info: "EvaluationErrorInfo" = proto.Field( + proto.MESSAGE, + number=10, + message="EvaluationErrorInfo", + ) + span_latencies: MutableSequence["EvaluationResult.SpanLatency"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=11, + message="EvaluationResult.SpanLatency", + ) + ) + + turn_replay_results: MutableSequence[ + "EvaluationResult.GoldenResult.TurnReplayResult" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="EvaluationResult.GoldenResult.TurnReplayResult", + ) + evaluation_expectation_results: MutableSequence[ + "EvaluationResult.EvaluationExpectationResult" + ] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="EvaluationResult.EvaluationExpectationResult", + ) + + class ScenarioRubricOutcome(proto.Message): + r"""The outcome of the evaluation against the rubric. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + rubric (str): + Output only. The rubric that was used to + evaluate the conversation. + score (float): + Output only. The score of the conversation + against the rubric. + + This field is a member of `oneof`_ ``_score``. + score_explanation (str): + Output only. The rater's response to the + rubric. + """ + + rubric: str = proto.Field( + proto.STRING, + number=1, + ) + score: float = proto.Field( + proto.FLOAT, + number=2, + optional=True, + ) + score_explanation: str = proto.Field( + proto.STRING, + number=3, + ) + + class ScenarioExpectationOutcome(proto.Message): + r"""The outcome of a scenario expectation. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + observed_tool_call (google.cloud.ces_v1beta.types.EvaluationResult.ScenarioExpectationOutcome.ObservedToolCall): + Output only. The observed tool call. + + This field is a member of `oneof`_ ``result``. + observed_agent_response (google.cloud.ces_v1beta.types.Message): + Output only. The observed agent response. + + This field is a member of `oneof`_ ``result``. + expectation (google.cloud.ces_v1beta.types.Evaluation.ScenarioExpectation): + Output only. The expectation that was + evaluated. + outcome (google.cloud.ces_v1beta.types.EvaluationResult.Outcome): + Output only. The outcome of the + ScenarioExpectation. + """ + + class ObservedToolCall(proto.Message): + r"""The observed tool call and response. + + Attributes: + tool_call (google.cloud.ces_v1beta.types.ToolCall): + Output only. The observed tool call. + tool_response (google.cloud.ces_v1beta.types.ToolResponse): + Output only. The observed tool response. + """ + + tool_call: example.ToolCall = proto.Field( + proto.MESSAGE, + number=1, + message=example.ToolCall, + ) + tool_response: example.ToolResponse = proto.Field( + proto.MESSAGE, + number=2, + message=example.ToolResponse, + ) + + observed_tool_call: "EvaluationResult.ScenarioExpectationOutcome.ObservedToolCall" = proto.Field( + proto.MESSAGE, + number=2, + oneof="result", + message="EvaluationResult.ScenarioExpectationOutcome.ObservedToolCall", + ) + observed_agent_response: example.Message = proto.Field( + proto.MESSAGE, + number=3, + oneof="result", + message=example.Message, + ) + expectation: "Evaluation.ScenarioExpectation" = proto.Field( + proto.MESSAGE, + number=1, + message="Evaluation.ScenarioExpectation", + ) + outcome: "EvaluationResult.Outcome" = proto.Field( + proto.ENUM, + number=4, + enum="EvaluationResult.Outcome", + ) + + class ScenarioResult(proto.Message): + r"""The outcome of a scenario evaluation. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + conversation (str): + Output only. The conversation that was + generated in the scenario. + task (str): + Output only. The task that was used when + running the scenario for this result. + user_facts (MutableSequence[google.cloud.ces_v1beta.types.Evaluation.Scenario.UserFact]): + Output only. The user facts that were used by + the scenario for this result. + expectation_outcomes (MutableSequence[google.cloud.ces_v1beta.types.EvaluationResult.ScenarioExpectationOutcome]): + Output only. The outcome of each expectation. + rubric_outcomes (MutableSequence[google.cloud.ces_v1beta.types.EvaluationResult.ScenarioRubricOutcome]): + Output only. The outcome of the rubric. + hallucination_result (MutableSequence[google.cloud.ces_v1beta.types.EvaluationResult.HallucinationResult]): + Output only. The result of the hallucination + check. There will be one hallucination result + for each turn in the conversation. + task_completion_result (google.cloud.ces_v1beta.types.EvaluationResult.TaskCompletionResult): + Output only. The result of the task + completion check. + tool_call_latencies (MutableSequence[google.cloud.ces_v1beta.types.EvaluationResult.ToolCallLatency]): + Output only. The latency of each tool call + execution in the conversation. + user_goal_satisfaction_result (google.cloud.ces_v1beta.types.EvaluationResult.UserGoalSatisfactionResult): + Output only. The result of the user goal + satisfaction check. + all_expectations_satisfied (bool): + Output only. Whether all expectations were + satisfied for this turn. + + This field is a member of `oneof`_ ``_all_expectations_satisfied``. + task_completed (bool): + Output only. Whether the task was completed + for this turn. This is a composite of all + expectations satisfied, no hallucinations, and + user goal satisfaction. + + This field is a member of `oneof`_ ``_task_completed``. + span_latencies (MutableSequence[google.cloud.ces_v1beta.types.EvaluationResult.SpanLatency]): + Output only. The latency of spans in the + conversation. + evaluation_expectation_results (MutableSequence[google.cloud.ces_v1beta.types.EvaluationResult.EvaluationExpectationResult]): + Output only. The results of the evaluation + expectations. + """ + + conversation: str = proto.Field( + proto.STRING, + number=1, + ) + task: str = proto.Field( + proto.STRING, + number=10, + ) + user_facts: MutableSequence["Evaluation.Scenario.UserFact"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=11, + message="Evaluation.Scenario.UserFact", + ) + ) + expectation_outcomes: MutableSequence[ + "EvaluationResult.ScenarioExpectationOutcome" + ] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="EvaluationResult.ScenarioExpectationOutcome", + ) + rubric_outcomes: MutableSequence["EvaluationResult.ScenarioRubricOutcome"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=3, + message="EvaluationResult.ScenarioRubricOutcome", + ) + ) + hallucination_result: MutableSequence[ + "EvaluationResult.HallucinationResult" + ] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message="EvaluationResult.HallucinationResult", + ) + task_completion_result: "EvaluationResult.TaskCompletionResult" = proto.Field( + proto.MESSAGE, + number=5, + message="EvaluationResult.TaskCompletionResult", + ) + tool_call_latencies: MutableSequence["EvaluationResult.ToolCallLatency"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=6, + message="EvaluationResult.ToolCallLatency", + ) + ) + user_goal_satisfaction_result: "EvaluationResult.UserGoalSatisfactionResult" = ( + proto.Field( + proto.MESSAGE, + number=7, + message="EvaluationResult.UserGoalSatisfactionResult", + ) + ) + all_expectations_satisfied: bool = proto.Field( + proto.BOOL, + number=8, + optional=True, + ) + task_completed: bool = proto.Field( + proto.BOOL, + number=9, + optional=True, + ) + span_latencies: MutableSequence["EvaluationResult.SpanLatency"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=12, + message="EvaluationResult.SpanLatency", + ) + ) + evaluation_expectation_results: MutableSequence[ + "EvaluationResult.EvaluationExpectationResult" + ] = proto.RepeatedField( + proto.MESSAGE, + number=13, + message="EvaluationResult.EvaluationExpectationResult", + ) + + class SpanLatency(proto.Message): + r"""The latency of a span execution. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + resource (str): + Output only. The resource name of the + guardrail or tool spans. + + This field is a member of `oneof`_ ``identifier``. + toolset (google.cloud.ces_v1beta.types.ToolsetTool): + Output only. The toolset tool identifier. + + This field is a member of `oneof`_ ``identifier``. + model (str): + Output only. The name of the LLM span. + + This field is a member of `oneof`_ ``identifier``. + callback (str): + Output only. The name of the user callback + span. + + This field is a member of `oneof`_ ``identifier``. + type_ (google.cloud.ces_v1beta.types.EvaluationResult.SpanLatency.Type): + Output only. The type of span. + display_name (str): + Output only. The display name of the span. + Applicable to tool and guardrail spans. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The start time of span. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The end time of span. + execution_latency (google.protobuf.duration_pb2.Duration): + Output only. The latency of span. + """ + + class Type(proto.Enum): + r"""The type of span. + Additional values may be added in the future. + + Values: + TYPE_UNSPECIFIED (0): + Default value. This value is unused. + TOOL (1): + Tool call span. + USER_CALLBACK (2): + User callback span. + GUARDRAIL (3): + Guardrail span. + LLM (4): + LLM span. + """ + + TYPE_UNSPECIFIED = 0 + TOOL = 1 + USER_CALLBACK = 2 + GUARDRAIL = 3 + LLM = 4 + + resource: str = proto.Field( + proto.STRING, + number=2, + oneof="identifier", + ) + toolset: gcc_toolset_tool.ToolsetTool = proto.Field( + proto.MESSAGE, + number=3, + oneof="identifier", + message=gcc_toolset_tool.ToolsetTool, + ) + model: str = proto.Field( + proto.STRING, + number=4, + oneof="identifier", + ) + callback: str = proto.Field( + proto.STRING, + number=5, + oneof="identifier", + ) + type_: "EvaluationResult.SpanLatency.Type" = proto.Field( + proto.ENUM, + number=1, + enum="EvaluationResult.SpanLatency.Type", + ) + display_name: str = proto.Field( + proto.STRING, + number=9, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + execution_latency: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=8, + message=duration_pb2.Duration, + ) + + class ToolCallLatency(proto.Message): + r"""The latency of a tool call execution. + + Attributes: + tool (str): + Output only. The name of the tool that got executed. Format: + ``projects/{project}/locations/{location}/apps/{app}/tools/{tool}``. + display_name (str): + Output only. The display name of the tool. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The start time of the tool call + execution. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The end time of the tool call + execution. + execution_latency (google.protobuf.duration_pb2.Duration): + Output only. The latency of the tool call + execution. + """ + + tool: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + execution_latency: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + + class HallucinationResult(proto.Message): + r"""The result of the hallucination check for a single turn. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + score (int): + Output only. The hallucination score. Can be + -1, 0, 1. + + This field is a member of `oneof`_ ``_score``. + label (str): + Output only. The label associated with each + score. Score 1: Justified + Score 0: Not Justified + Score -1: No Claim To Assess + explanation (str): + Output only. The explanation for the + hallucination score. + """ + + score: int = proto.Field( + proto.INT32, + number=1, + optional=True, + ) + label: str = proto.Field( + proto.STRING, + number=2, + ) + explanation: str = proto.Field( + proto.STRING, + number=3, + ) + + class UserGoalSatisfactionResult(proto.Message): + r"""The result of a user goal satisfaction check for a + conversation. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + score (int): + Output only. The user task satisfaction + score. Can be -1, 0, 1. + + This field is a member of `oneof`_ ``_score``. + label (str): + Output only. The label associated with each + score. Score 1: User Task Satisfied + Score 0: User Task Not Satisfied + Score -1: User Task Unspecified + explanation (str): + Output only. The explanation for the user + task satisfaction score. + """ + + score: int = proto.Field( + proto.INT32, + number=1, + optional=True, + ) + label: str = proto.Field( + proto.STRING, + number=2, + ) + explanation: str = proto.Field( + proto.STRING, + number=3, + ) + + class SemanticSimilarityResult(proto.Message): + r"""The result of the semantic similarity check. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + score (int): + Output only. The semantic similarity score. + Can be 0, 1, 2, 3, or 4. + + This field is a member of `oneof`_ ``_score``. + label (str): + Output only. The label associated with each + score. Score 4: Fully Consistent + Score 3: Mostly Consistent + Score 2: Partially Consistent (Minor Omissions) + Score 1: Largely Inconsistent (Major Omissions) + Score 0: Completely Inconsistent / Contradictory + explanation (str): + Output only. The explanation for the semantic + similarity score. + outcome (google.cloud.ces_v1beta.types.EvaluationResult.Outcome): + Output only. The outcome of the semantic similarity check. + This is determined by comparing the score to the + semantic_similarity_success_threshold. If the score is equal + to or above the threshold, the outcome will be PASS. + Otherwise, the outcome will be FAIL. + """ + + score: int = proto.Field( + proto.INT32, + number=1, + optional=True, + ) + label: str = proto.Field( + proto.STRING, + number=2, + ) + explanation: str = proto.Field( + proto.STRING, + number=3, + ) + outcome: "EvaluationResult.Outcome" = proto.Field( + proto.ENUM, + number=4, + enum="EvaluationResult.Outcome", + ) + + class OverallToolInvocationResult(proto.Message): + r"""The result of the overall tool invocation check. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + tool_invocation_score (float): + The overall tool invocation score for this + turn. This indicates the overall percent of + tools from the expected turn that were actually + invoked. + + This field is a member of `oneof`_ ``_tool_invocation_score``. + outcome (google.cloud.ces_v1beta.types.EvaluationResult.Outcome): + Output only. The outcome of the tool invocation check. This + is determined by comparing the tool_invocation_score to the + overall_tool_invocation_correctness_threshold. If the score + is equal to or above the threshold, the outcome will be + PASS. Otherwise, the outcome will be FAIL. + """ + + tool_invocation_score: float = proto.Field( + proto.FLOAT, + number=1, + optional=True, + ) + outcome: "EvaluationResult.Outcome" = proto.Field( + proto.ENUM, + number=2, + enum="EvaluationResult.Outcome", + ) + + class TaskCompletionResult(proto.Message): + r"""The result of the task completion check for the conversation. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + score (int): + Output only. The task completion score. Can + be -1, 0, 1 + + This field is a member of `oneof`_ ``_score``. + label (str): + Output only. The label associated with each + score. Score 1: Task Completed + Score 0: Task Not Completed + Score -1: User Goal Undefined + explanation (str): + Output only. The explanation for the task + completion score. + """ + + score: int = proto.Field( + proto.INT32, + number=1, + optional=True, + ) + label: str = proto.Field( + proto.STRING, + number=2, + ) + explanation: str = proto.Field( + proto.STRING, + number=3, + ) + + golden_result: GoldenResult = proto.Field( + proto.MESSAGE, + number=7, + oneof="result", + message=GoldenResult, + ) + scenario_result: ScenarioResult = proto.Field( + proto.MESSAGE, + number=8, + oneof="result", + message=ScenarioResult, + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + evaluation_status: Outcome = proto.Field( + proto.ENUM, + number=4, + enum=Outcome, + ) + evaluation_run: str = proto.Field( + proto.STRING, + number=6, + ) + persona: gcc_app.EvaluationPersona = proto.Field( + proto.MESSAGE, + number=17, + message=gcc_app.EvaluationPersona, + ) + error_info: "EvaluationErrorInfo" = proto.Field( + proto.MESSAGE, + number=15, + message="EvaluationErrorInfo", + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=14, + message=status_pb2.Status, + ) + initiated_by: str = proto.Field( + proto.STRING, + number=9, + ) + app_version: str = proto.Field( + proto.STRING, + number=10, + ) + app_version_display_name: str = proto.Field( + proto.STRING, + number=13, + ) + changelog: str = proto.Field( + proto.STRING, + number=21, + ) + changelog_create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=22, + message=timestamp_pb2.Timestamp, + ) + execution_state: ExecutionState = proto.Field( + proto.ENUM, + number=11, + enum=ExecutionState, + ) + evaluation_metrics_thresholds: gcc_app.EvaluationMetricsThresholds = proto.Field( + proto.MESSAGE, + number=12, + message=gcc_app.EvaluationMetricsThresholds, + ) + config: "EvaluationConfig" = proto.Field( + proto.MESSAGE, + number=18, + message="EvaluationConfig", + ) + golden_run_method: golden_run.GoldenRunMethod = proto.Field( + proto.ENUM, + number=19, + enum=golden_run.GoldenRunMethod, + ) + + +class EvaluationRun(proto.Message): + r"""An evaluation run represents an all the evaluation results + from an evaluation execution. + + Attributes: + name (str): + Identifier. The unique identifier of the evaluation run. + Format: + ``projects/{project}/locations/{location}/apps/{app}/evaluationRuns/{evaluationRun}`` + display_name (str): + Optional. User-defined display name of the + evaluation run. default: + " run - + ". + evaluation_results (MutableSequence[str]): + Output only. The evaluation results that are part of this + run. Format: + ``projects/{project}/locations/{location}/apps/{app}/evaluations/{evaluation}/results/{result}`` + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the evaluation + run was created. + initiated_by (str): + Output only. The user who initiated the + evaluation run. + app_version (str): + Output only. The app version to evaluate. Format: + ``projects/{project}/locations/{location}/apps/{app}/versions/{version}`` + app_version_display_name (str): + Output only. The display name of the ``app_version`` that + the evaluation ran against. + changelog (str): + Output only. The changelog of the app version + that the evaluation ran against. This is + populated if user runs evaluation on + latest/draft. + changelog_create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The create time of the changelog + of the app version that the evaluation ran + against. This is populated if user runs + evaluation on latest/draft. + evaluations (MutableSequence[str]): + Output only. The evaluations that are part of this run. The + list may contain evaluations of either type. This field is + mutually exclusive with ``evaluation_dataset``. Format: + ``projects/{project}/locations/{location}/apps/{app}/evaluations/{evaluation}`` + evaluation_dataset (str): + Output only. The evaluation dataset that this run is + associated with. This field is mutually exclusive with + ``evaluations``. Format: + ``projects/{project}/locations/{location}/apps/{app}/evaluationDatasets/{evaluationDataset}`` + evaluation_type (google.cloud.ces_v1beta.types.EvaluationRun.EvaluationType): + Output only. The type of the evaluations in + this run. + state (google.cloud.ces_v1beta.types.EvaluationRun.EvaluationRunState): + Output only. The state of the evaluation run. + progress (google.cloud.ces_v1beta.types.EvaluationRun.Progress): + Output only. The progress of the evaluation + run. + config (google.cloud.ces_v1beta.types.EvaluationConfig): + Output only. The configuration used in the + run. + error (google.rpc.status_pb2.Status): + Output only. Deprecated: Use error_info instead. Errors + encountered during execution. + error_info (google.cloud.ces_v1beta.types.EvaluationErrorInfo): + Output only. Error information for the + evaluation run. + evaluation_run_summaries (MutableMapping[str, google.cloud.ces_v1beta.types.EvaluationRun.EvaluationRunSummary]): + Output only. Map of evaluation name to + EvaluationRunSummary. + latency_report (google.cloud.ces_v1beta.types.LatencyReport): + Output only. Latency report for the + evaluation run. + run_count (int): + Output only. The number of times the + evaluations inside the run were run. + persona_run_configs (MutableSequence[google.cloud.ces_v1beta.types.PersonaRunConfig]): + Output only. The configuration to use for the + run per persona. + optimization_config (google.cloud.ces_v1beta.types.OptimizationConfig): + Optional. Configuration for running the + optimization step after the evaluation run. If + not set, the optimization step will not be run. + scheduled_evaluation_run (str): + Output only. The scheduled evaluation run resource name that + created this evaluation run. This field is only set if the + evaluation run was created by a scheduled evaluation run. + Format: + ``projects/{project}/locations/{location}/apps/{app}/scheduledEvaluationRuns/{scheduled_evaluation_run}`` + golden_run_method (google.cloud.ces_v1beta.types.GoldenRunMethod): + Output only. The method used to run the + evaluation. + """ + + class EvaluationType(proto.Enum): + r"""The type of the evaluations in this run. + Additional values may be added in the future. + + Values: + EVALUATION_TYPE_UNSPECIFIED (0): + Evaluation type is not specified. + GOLDEN (1): + Golden evaluation. + SCENARIO (2): + Scenario evaluation. + MIXED (3): + Indicates the run includes a mix of golden + and scenario evaluations. + """ + + EVALUATION_TYPE_UNSPECIFIED = 0 + GOLDEN = 1 + SCENARIO = 2 + MIXED = 3 + + class EvaluationRunState(proto.Enum): + r"""The state of the evaluation run. + + Values: + EVALUATION_RUN_STATE_UNSPECIFIED (0): + Evaluation run state is not specified. + RUNNING (1): + Evaluation run is running. + COMPLETED (2): + Evaluation run has completed. + ERROR (3): + The evaluation run has an error. + """ + + EVALUATION_RUN_STATE_UNSPECIFIED = 0 + RUNNING = 1 + COMPLETED = 2 + ERROR = 3 + + class Progress(proto.Message): + r"""The progress of the evaluation run. + + Attributes: + total_count (int): + Output only. Total number of evaluation + results in this run. + failed_count (int): + Output only. Number of completed evaluation results with an + outcome of FAIL. (EvaluationResult.execution_state is + COMPLETED and EvaluationResult.evaluation_status is FAIL). + error_count (int): + Output only. Number of evaluation results that failed to + execute. (EvaluationResult.execution_state is ERROR). + completed_count (int): + Output only. Number of evaluation results that finished + successfully. (EvaluationResult.execution_state is + COMPLETED). + passed_count (int): + Output only. Number of completed evaluation results with an + outcome of PASS. (EvaluationResult.execution_state is + COMPLETED and EvaluationResult.evaluation_status is PASS). + """ + + total_count: int = proto.Field( + proto.INT32, + number=1, + ) + failed_count: int = proto.Field( + proto.INT32, + number=2, + ) + error_count: int = proto.Field( + proto.INT32, + number=3, + ) + completed_count: int = proto.Field( + proto.INT32, + number=4, + ) + passed_count: int = proto.Field( + proto.INT32, + number=5, + ) + + class EvaluationRunSummary(proto.Message): + r"""Contains the summary of passed and failed result counts for a + specific evaluation in an evaluation run. + + Attributes: + passed_count (int): + Output only. Number of passed results for the + associated Evaluation in this run. + failed_count (int): + Output only. Number of failed results for the + associated Evaluation in this run. + error_count (int): + Output only. Number of error results for the + associated Evaluation in this run. + """ + + passed_count: int = proto.Field( + proto.INT32, + number=1, + ) + failed_count: int = proto.Field( + proto.INT32, + number=2, + ) + error_count: int = proto.Field( + proto.INT32, + number=3, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + evaluation_results: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + initiated_by: str = proto.Field( + proto.STRING, + number=5, + ) + app_version: str = proto.Field( + proto.STRING, + number=6, + ) + app_version_display_name: str = proto.Field( + proto.STRING, + number=13, + ) + changelog: str = proto.Field( + proto.STRING, + number=22, + ) + changelog_create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=23, + message=timestamp_pb2.Timestamp, + ) + evaluations: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + evaluation_dataset: str = proto.Field( + proto.STRING, + number=8, + ) + evaluation_type: EvaluationType = proto.Field( + proto.ENUM, + number=9, + enum=EvaluationType, + ) + state: EvaluationRunState = proto.Field( + proto.ENUM, + number=10, + enum=EvaluationRunState, + ) + progress: Progress = proto.Field( + proto.MESSAGE, + number=11, + message=Progress, + ) + config: "EvaluationConfig" = proto.Field( + proto.MESSAGE, + number=12, + message="EvaluationConfig", + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=14, + message=status_pb2.Status, + ) + error_info: "EvaluationErrorInfo" = proto.Field( + proto.MESSAGE, + number=17, + message="EvaluationErrorInfo", + ) + evaluation_run_summaries: MutableMapping[str, EvaluationRunSummary] = ( + proto.MapField( + proto.STRING, + proto.MESSAGE, + number=15, + message=EvaluationRunSummary, + ) + ) + latency_report: "LatencyReport" = proto.Field( + proto.MESSAGE, + number=25, + message="LatencyReport", + ) + run_count: int = proto.Field( + proto.INT32, + number=16, + ) + persona_run_configs: MutableSequence["PersonaRunConfig"] = proto.RepeatedField( + proto.MESSAGE, + number=18, + message="PersonaRunConfig", + ) + optimization_config: "OptimizationConfig" = proto.Field( + proto.MESSAGE, + number=19, + message="OptimizationConfig", + ) + scheduled_evaluation_run: str = proto.Field( + proto.STRING, + number=20, + ) + golden_run_method: golden_run.GoldenRunMethod = proto.Field( + proto.ENUM, + number=21, + enum=golden_run.GoldenRunMethod, + ) + + +class LatencyReport(proto.Message): + r"""Latency report for the evaluation run. + + Attributes: + tool_latencies (MutableSequence[google.cloud.ces_v1beta.types.LatencyReport.ToolLatency]): + Output only. Unordered list. Latency metrics + for each tool. + callback_latencies (MutableSequence[google.cloud.ces_v1beta.types.LatencyReport.CallbackLatency]): + Output only. Unordered list. Latency metrics + for each callback. + guardrail_latencies (MutableSequence[google.cloud.ces_v1beta.types.LatencyReport.GuardrailLatency]): + Output only. Unordered list. Latency metrics + for each guardrail. + llm_call_latencies (MutableSequence[google.cloud.ces_v1beta.types.LatencyReport.LlmCallLatency]): + Output only. Unordered list. Latency metrics + for each LLM call. + session_count (int): + Output only. The total number of sessions + considered in the latency report. + """ + + class LatencyMetrics(proto.Message): + r"""Latency metrics for a component. + + Attributes: + p50_latency (google.protobuf.duration_pb2.Duration): + Output only. The 50th percentile latency. + p90_latency (google.protobuf.duration_pb2.Duration): + Output only. The 90th percentile latency. + p99_latency (google.protobuf.duration_pb2.Duration): + Output only. The 99th percentile latency. + call_count (int): + Output only. The number of times the resource + was called. + """ + + p50_latency: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + p90_latency: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + p99_latency: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + call_count: int = proto.Field( + proto.INT32, + number=4, + ) + + class ToolLatency(proto.Message): + r"""Latency metrics for a single tool. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + tool (str): + Output only. Format: + ``projects/{project}/locations/{location}/apps/{app}/tools/{tool}``. + + This field is a member of `oneof`_ ``tool_identifier``. + toolset_tool (google.cloud.ces_v1beta.types.ToolsetTool): + Output only. The toolset tool identifier. + + This field is a member of `oneof`_ ``tool_identifier``. + tool_display_name (str): + Output only. The display name of the tool. + latency_metrics (google.cloud.ces_v1beta.types.LatencyReport.LatencyMetrics): + Output only. The latency metrics for the + tool. + """ + + tool: str = proto.Field( + proto.STRING, + number=1, + oneof="tool_identifier", + ) + toolset_tool: gcc_toolset_tool.ToolsetTool = proto.Field( + proto.MESSAGE, + number=2, + oneof="tool_identifier", + message=gcc_toolset_tool.ToolsetTool, + ) + tool_display_name: str = proto.Field( + proto.STRING, + number=3, + ) + latency_metrics: "LatencyReport.LatencyMetrics" = proto.Field( + proto.MESSAGE, + number=4, + message="LatencyReport.LatencyMetrics", + ) + + class CallbackLatency(proto.Message): + r"""Latency metrics for a single callback. + + Attributes: + stage (str): + Output only. The stage of the callback. + latency_metrics (google.cloud.ces_v1beta.types.LatencyReport.LatencyMetrics): + Output only. The latency metrics for the + callback. + """ + + stage: str = proto.Field( + proto.STRING, + number=1, + ) + latency_metrics: "LatencyReport.LatencyMetrics" = proto.Field( + proto.MESSAGE, + number=2, + message="LatencyReport.LatencyMetrics", + ) + + class GuardrailLatency(proto.Message): + r"""Latency metrics for a single guardrail. + + Attributes: + guardrail (str): + Output only. The name of the guardrail. Format: + ``projects/{project}/locations/{location}/apps/{app}/guardrails/{guardrail}``. + guardrail_display_name (str): + Output only. The display name of the + guardrail. + latency_metrics (google.cloud.ces_v1beta.types.LatencyReport.LatencyMetrics): + Output only. The latency metrics for the + guardrail. + """ + + guardrail: str = proto.Field( + proto.STRING, + number=1, + ) + guardrail_display_name: str = proto.Field( + proto.STRING, + number=2, + ) + latency_metrics: "LatencyReport.LatencyMetrics" = proto.Field( + proto.MESSAGE, + number=3, + message="LatencyReport.LatencyMetrics", + ) + + class LlmCallLatency(proto.Message): + r"""Latency metrics for a single LLM call. + + Attributes: + model (str): + Output only. The name of the model. + latency_metrics (google.cloud.ces_v1beta.types.LatencyReport.LatencyMetrics): + Output only. The latency metrics for the LLM + call. + """ + + model: str = proto.Field( + proto.STRING, + number=1, + ) + latency_metrics: "LatencyReport.LatencyMetrics" = proto.Field( + proto.MESSAGE, + number=2, + message="LatencyReport.LatencyMetrics", + ) + + tool_latencies: MutableSequence[ToolLatency] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=ToolLatency, + ) + callback_latencies: MutableSequence[CallbackLatency] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=CallbackLatency, + ) + guardrail_latencies: MutableSequence[GuardrailLatency] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=GuardrailLatency, + ) + llm_call_latencies: MutableSequence[LlmCallLatency] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=LlmCallLatency, + ) + session_count: int = proto.Field( + proto.INT32, + number=5, + ) + + +class EvaluationExpectation(proto.Message): + r"""An evaluation expectation represents a specific criteria to + evaluate against. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + llm_criteria (google.cloud.ces_v1beta.types.EvaluationExpectation.LlmCriteria): + Optional. Evaluation criteria based on an LLM + prompt. + + This field is a member of `oneof`_ ``criteria``. + name (str): + Identifier. The unique identifier of this evaluation + expectation. Format: + ``projects/{project}/locations/{location}/apps/{app}/evaluationExpectations/{evaluation_expectation}`` + display_name (str): + Required. User-defined display name. Must be + unique within the app. + tags (MutableSequence[str]): + Optional. User-defined tags for expectations. + Can be used to filter expectations. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the evaluation + expectation was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the evaluation + expectation was last updated. + etag (str): + Output only. Etag used to ensure the object + hasn't changed during a read-modify-write + operation. If the etag is empty, the update will + overwrite any concurrent changes. + """ + + class LlmCriteria(proto.Message): + r"""Configuration for LLM-based evaluation criteria. + + Attributes: + prompt (str): + Required. The prompt/instructions provided to + the LLM judge. + """ + + prompt: str = proto.Field( + proto.STRING, + number=1, + ) + + llm_criteria: LlmCriteria = proto.Field( + proto.MESSAGE, + number=3, + oneof="criteria", + message=LlmCriteria, + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + tags: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=8, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + etag: str = proto.Field( + proto.STRING, + number=6, + ) + + +class EvaluationConfig(proto.Message): + r"""EvaluationConfig configures settings for running the + evaluation. + + Attributes: + input_audio_config (google.cloud.ces_v1beta.types.InputAudioConfig): + Optional. Configuration for processing the + input audio. + output_audio_config (google.cloud.ces_v1beta.types.OutputAudioConfig): + Optional. Configuration for generating the + output audio. + evaluation_channel (google.cloud.ces_v1beta.types.EvaluationConfig.EvaluationChannel): + Optional. The channel to evaluate. + tool_call_behaviour (google.cloud.ces_v1beta.types.EvaluationToolCallBehaviour): + Optional. Specifies whether the evaluation + should use real tool calls or fake tools. + """ + + class EvaluationChannel(proto.Enum): + r"""The channel to evaluate. + + Values: + EVALUATION_CHANNEL_UNSPECIFIED (0): + Unspecified evaluation channel. + TEXT (1): + Text-only evaluation channel. + AUDIO (2): + Audio evaluation channel. + """ + + EVALUATION_CHANNEL_UNSPECIFIED = 0 + TEXT = 1 + AUDIO = 2 + + input_audio_config: session_service.InputAudioConfig = proto.Field( + proto.MESSAGE, + number=1, + message=session_service.InputAudioConfig, + ) + output_audio_config: session_service.OutputAudioConfig = proto.Field( + proto.MESSAGE, + number=2, + message=session_service.OutputAudioConfig, + ) + evaluation_channel: EvaluationChannel = proto.Field( + proto.ENUM, + number=3, + enum=EvaluationChannel, + ) + tool_call_behaviour: fakes.EvaluationToolCallBehaviour = proto.Field( + proto.ENUM, + number=4, + enum=fakes.EvaluationToolCallBehaviour, + ) + + +class EvaluationErrorInfo(proto.Message): + r"""Information about an error encountered during an evaluation + execution. + + Attributes: + error_type (google.cloud.ces_v1beta.types.EvaluationErrorInfo.ErrorType): + Output only. The type of error. + error_message (str): + Output only. The error message. + session_id (str): + Output only. The session ID for the + conversation that caused the error. + """ + + class ErrorType(proto.Enum): + r"""The type of error + + Values: + ERROR_TYPE_UNSPECIFIED (0): + Unspecified error type. + RUNTIME_FAILURE (1): + Failure during runtime execution. + CONVERSATION_RETRIEVAL_FAILURE (2): + Failure to retrieve conversation from CES + Runtime. + METRIC_CALCULATION_FAILURE (3): + Failure to calculate a metric / outcome. + EVALUATION_UPDATE_FAILURE (4): + Failure to update the evaluation. + QUOTA_EXHAUSTED (5): + Ran out of quota. + USER_SIMULATION_FAILURE (6): + Failure during user simulation. + """ + + ERROR_TYPE_UNSPECIFIED = 0 + RUNTIME_FAILURE = 1 + CONVERSATION_RETRIEVAL_FAILURE = 2 + METRIC_CALCULATION_FAILURE = 3 + EVALUATION_UPDATE_FAILURE = 4 + QUOTA_EXHAUSTED = 5 + USER_SIMULATION_FAILURE = 6 + + error_type: ErrorType = proto.Field( + proto.ENUM, + number=1, + enum=ErrorType, + ) + error_message: str = proto.Field( + proto.STRING, + number=2, + ) + session_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class RunEvaluationRequest(proto.Message): + r"""Request message for + [EvaluationService.RunEvaluation][google.cloud.ces.v1beta.EvaluationService.RunEvaluation]. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + app (str): + Required. The app to evaluate. Format: + ``projects/{project}/locations/{location}/apps/{app}`` + evaluations (MutableSequence[str]): + Optional. List of evaluations to run. Format: + ``projects/{project}/locations/{location}/apps/{app}/evaluations/{evaluation}`` + evaluation_dataset (str): + Optional. An evaluation dataset to run. Format: + ``projects/{project}/locations/{location}/apps/{app}/evaluationDatasets/{evaluationDataset}`` + display_name (str): + Optional. The display name of the evaluation + run. + app_version (str): + Optional. The app version to evaluate. Format: + ``projects/{project}/locations/{location}/apps/{app}/versions/{version}`` + config (google.cloud.ces_v1beta.types.EvaluationConfig): + Optional. The configuration to use for the + run. + run_count (int): + Optional. The number of times to run the + evaluation. If not set, the default value is 1 + per golden, and 5 per scenario. + + This field is a member of `oneof`_ ``_run_count``. + persona_run_configs (MutableSequence[google.cloud.ces_v1beta.types.PersonaRunConfig]): + Optional. The configuration to use for the + run per persona. + optimization_config (google.cloud.ces_v1beta.types.OptimizationConfig): + Optional. Configuration for running the + optimization step after the evaluation run. If + not set, the optimization step will not be run. + scheduled_evaluation_run (str): + Optional. The resource name of the + ``ScheduledEvaluationRun`` that is triggering this + evaluation run. + + If this field is set, the ``scheduled_evaluation_run`` field + on the created ``EvaluationRun`` resource will be populated + from this value. Format: + ``projects/{project}/locations/{location}/apps/{app}/scheduledEvaluationRuns/{scheduled_evaluation_run}`` + golden_run_method (google.cloud.ces_v1beta.types.GoldenRunMethod): + Optional. The method to run the evaluation if + it is a golden evaluation. If not set, default + to STABLE. + generate_latency_report (bool): + Optional. Whether to generate a latency + report for the evaluation run. + """ + + app: str = proto.Field( + proto.STRING, + number=1, + ) + evaluations: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + evaluation_dataset: str = proto.Field( + proto.STRING, + number=3, + ) + display_name: str = proto.Field( + proto.STRING, + number=4, + ) + app_version: str = proto.Field( + proto.STRING, + number=6, + ) + config: "EvaluationConfig" = proto.Field( + proto.MESSAGE, + number=8, + message="EvaluationConfig", + ) + run_count: int = proto.Field( + proto.INT32, + number=9, + optional=True, + ) + persona_run_configs: MutableSequence["PersonaRunConfig"] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message="PersonaRunConfig", + ) + optimization_config: "OptimizationConfig" = proto.Field( + proto.MESSAGE, + number=11, + message="OptimizationConfig", + ) + scheduled_evaluation_run: str = proto.Field( + proto.STRING, + number=12, + ) + golden_run_method: golden_run.GoldenRunMethod = proto.Field( + proto.ENUM, + number=13, + enum=golden_run.GoldenRunMethod, + ) + generate_latency_report: bool = proto.Field( + proto.BOOL, + number=14, + ) + + +class ScheduledEvaluationRun(proto.Message): + r"""Represents a scheduled evaluation run configuration. + + Attributes: + name (str): + Identifier. The unique identifier of the + scheduled evaluation run config. Format: + + projects/{projectId}/locations/{locationId}/apps/{appId}/scheduledEvaluationRuns/{scheduledEvaluationRunId} + display_name (str): + Required. User-defined display name of the + scheduled evaluation run config. + request (google.cloud.ces_v1beta.types.RunEvaluationRequest): + Required. The RunEvaluationRequest to + schedule + description (str): + Optional. User-defined description of the + scheduled evaluation run. + scheduling_config (google.cloud.ces_v1beta.types.ScheduledEvaluationRun.SchedulingConfig): + Required. Configuration for the timing and + frequency with which to execute the evaluations. + active (bool): + Optional. Whether this config is active + last_completed_run (str): + Output only. The last successful EvaluationRun of this + scheduled execution. Format: + ``projects/{project}/locations/{location}/apps/{app}/evaluationRuns/{evaluationRun}`` + total_executions (int): + Output only. The total number of times this + run has been executed + next_scheduled_execution_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The next time this is scheduled + to execute + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the scheduled + evaluation run was created. + created_by (str): + Output only. The user who created the + scheduled evaluation run. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the evaluation + was last updated. + last_updated_by (str): + Output only. The user who last updated the + evaluation. + etag (str): + Output only. Etag used to ensure the object + hasn't changed during a read-modify-write + operation. If the etag is empty, the update will + overwrite any concurrent changes. + """ + + class SchedulingConfig(proto.Message): + r"""Eval scheduling configuration details + + Attributes: + frequency (google.cloud.ces_v1beta.types.ScheduledEvaluationRun.SchedulingConfig.Frequency): + Required. The frequency with which to run the + eval + start_time (google.protobuf.timestamp_pb2.Timestamp): + Required. Timestamp when the eval should + start. + days_of_week (MutableSequence[int]): + Optional. The days of the week to run the + eval. Applicable only for Weekly and Biweekly + frequencies. 1 is Monday, 2 is Tuesday, ..., 7 + is Sunday. + """ + + class Frequency(proto.Enum): + r"""The frequencies evals can be run at + + Values: + FREQUENCY_UNSPECIFIED (0): + The frequency is unspecified. + NONE (1): + Indicates a one-time scheduled run that + should not repeat + DAILY (2): + Run the evaluation daily. + WEEKLY (3): + Run the evaluation weekly. + BIWEEKLY (4): + Run the evaluation biweekly. + """ + + FREQUENCY_UNSPECIFIED = 0 + NONE = 1 + DAILY = 2 + WEEKLY = 3 + BIWEEKLY = 4 + + frequency: "ScheduledEvaluationRun.SchedulingConfig.Frequency" = proto.Field( + proto.ENUM, + number=1, + enum="ScheduledEvaluationRun.SchedulingConfig.Frequency", + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + days_of_week: MutableSequence[int] = proto.RepeatedField( + proto.INT32, + number=3, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + request: "RunEvaluationRequest" = proto.Field( + proto.MESSAGE, + number=3, + message="RunEvaluationRequest", + ) + description: str = proto.Field( + proto.STRING, + number=4, + ) + scheduling_config: SchedulingConfig = proto.Field( + proto.MESSAGE, + number=5, + message=SchedulingConfig, + ) + active: bool = proto.Field( + proto.BOOL, + number=6, + ) + last_completed_run: str = proto.Field( + proto.STRING, + number=7, + ) + total_executions: int = proto.Field( + proto.INT32, + number=8, + ) + next_scheduled_execution_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + created_by: str = proto.Field( + proto.STRING, + number=11, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=12, + message=timestamp_pb2.Timestamp, + ) + last_updated_by: str = proto.Field( + proto.STRING, + number=13, + ) + etag: str = proto.Field( + proto.STRING, + number=14, + ) + + +class PersonaRunConfig(proto.Message): + r"""Configuration for running an evaluation for a specific + persona. + + Attributes: + persona (str): + Optional. The persona to use for the evaluation. Format: + ``projects/{project}/locations/{location}/apps/{app}/evaluationPersonas/{evaluationPersona}`` + task_count (int): + Optional. The number of tasks to run for the + persona. + """ + + persona: str = proto.Field( + proto.STRING, + number=1, + ) + task_count: int = proto.Field( + proto.INT32, + number=2, + ) + + +class OptimizationConfig(proto.Message): + r"""Configuration for running the optimization step after the + evaluation run. + + Attributes: + generate_loss_report (bool): + Optional. Whether to generate a loss report. + assistant_session (str): + Output only. The assistant session to use for the + optimization based on this evaluation run. Format: + ``projects/{project}/locations/{location}/apps/{app}/assistantSessions/{assistantSession}`` + report_summary (str): + Output only. The summary of the loss report. + should_suggest_fix (bool): + Output only. Whether to suggest a fix for the + losses. + status (google.cloud.ces_v1beta.types.OptimizationConfig.OptimizationStatus): + Output only. The status of the optimization + run. + error_message (str): + Output only. The error message if the + optimization run failed. + loss_report (google.protobuf.struct_pb2.Struct): + Output only. The generated loss report. + """ + + class OptimizationStatus(proto.Enum): + r"""The status of the optimization run. + + Values: + OPTIMIZATION_STATUS_UNSPECIFIED (0): + Optimization status is not specified. + RUNNING (1): + Optimization is running. + COMPLETED (2): + Optimization has completed. + ERROR (3): + Optimization failed due to an internal error. + """ + + OPTIMIZATION_STATUS_UNSPECIFIED = 0 + RUNNING = 1 + COMPLETED = 2 + ERROR = 3 + + generate_loss_report: bool = proto.Field( + proto.BOOL, + number=1, + ) + assistant_session: str = proto.Field( + proto.STRING, + number=2, + ) + report_summary: str = proto.Field( + proto.STRING, + number=3, + ) + should_suggest_fix: bool = proto.Field( + proto.BOOL, + number=5, + ) + status: OptimizationStatus = proto.Field( + proto.ENUM, + number=4, + enum=OptimizationStatus, + ) + error_message: str = proto.Field( + proto.STRING, + number=6, + ) + loss_report: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=7, + message=struct_pb2.Struct, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/evaluation_service.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/evaluation_service.py new file mode 100644 index 000000000000..aa9ed54f3164 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/evaluation_service.py @@ -0,0 +1,1496 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.ces_v1beta.types import conversation as gcc_conversation +from google.cloud.ces_v1beta.types import evaluation as gcc_evaluation + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "RunEvaluationResponse", + "RunEvaluationOperationMetadata", + "GenerateEvaluationOperationMetadata", + "DeleteEvaluationRunOperationMetadata", + "CreateEvaluationRequest", + "GenerateEvaluationRequest", + "ImportEvaluationsRequest", + "ImportEvaluationsResponse", + "ImportEvaluationsOperationMetadata", + "CreateEvaluationDatasetRequest", + "UpdateEvaluationRequest", + "UpdateEvaluationDatasetRequest", + "DeleteEvaluationRequest", + "DeleteEvaluationResultRequest", + "DeleteEvaluationDatasetRequest", + "DeleteEvaluationRunRequest", + "GetEvaluationRequest", + "GetEvaluationResultRequest", + "GetEvaluationDatasetRequest", + "GetEvaluationRunRequest", + "ListEvaluationsRequest", + "ListEvaluationResultsRequest", + "ListEvaluationDatasetsRequest", + "ListEvaluationRunsRequest", + "ListEvaluationsResponse", + "ListEvaluationResultsResponse", + "ListEvaluationDatasetsResponse", + "ListEvaluationRunsResponse", + "CreateScheduledEvaluationRunRequest", + "GetScheduledEvaluationRunRequest", + "ListScheduledEvaluationRunsRequest", + "ListScheduledEvaluationRunsResponse", + "UpdateScheduledEvaluationRunRequest", + "DeleteScheduledEvaluationRunRequest", + "TestPersonaVoiceRequest", + "UploadEvaluationAudioRequest", + "UploadEvaluationAudioResponse", + "TestPersonaVoiceResponse", + "CreateEvaluationExpectationRequest", + "UpdateEvaluationExpectationRequest", + "DeleteEvaluationExpectationRequest", + "GetEvaluationExpectationRequest", + "ListEvaluationExpectationsRequest", + "ListEvaluationExpectationsResponse", + }, +) + + +class RunEvaluationResponse(proto.Message): + r"""Response message for + [EvaluationService.RunEvaluation][google.cloud.ces.v1beta.EvaluationService.RunEvaluation]. + + Attributes: + evaluation_run (str): + The name of the evaluation run that was created. Format: + ``projects/{project}/locations/{location}/apps/{app}/evaluationRuns/{evaluation_run}`` + """ + + evaluation_run: str = proto.Field( + proto.STRING, + number=1, + ) + + +class RunEvaluationOperationMetadata(proto.Message): + r"""Operation metadata for + [EvaluationService.RunEvaluation][google.cloud.ces.v1beta.EvaluationService.RunEvaluation] + + Attributes: + evaluations (MutableSequence[str]): + Output only. The list of evaluations that were run. Format: + ``projects/{project}/locations/{location}/apps/{app}/evaluations/{evaluation}`` + evaluation_run (str): + Output only. The evaluation run that was created. Format: + ``projects/{project}/locations/{location}/apps/{app}/evaluationRuns/{evaluation_run}`` + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation was + created. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation + completed. + verb (str): + Output only. The verb of the operation. + cancel_requested (bool): + Output only. Identifies whether the user has requested + cancellation of the operation. Operations that have been + cancelled successfully have + [google.longrunning.Operation.error][google.longrunning.Operation.error] + value with a + [google.rpc.Status.code][google.rpc.Status.code] of ``1``, + corresponding to ``Code.CANCELLED``. + """ + + evaluations: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + evaluation_run: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + verb: str = proto.Field( + proto.STRING, + number=5, + ) + cancel_requested: bool = proto.Field( + proto.BOOL, + number=6, + ) + + +class GenerateEvaluationOperationMetadata(proto.Message): + r"""Operation metadata for + [EvaluationService.GenerateEvaluation][google.cloud.ces.v1beta.EvaluationService.GenerateEvaluation]. + + """ + + +class DeleteEvaluationRunOperationMetadata(proto.Message): + r"""Operation metadata for + [EvaluationService.DeleteEvaluationRun][google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationRun]. + + """ + + +class CreateEvaluationRequest(proto.Message): + r"""Request message for + [EvaluationService.CreateEvaluation][google.cloud.ces.v1beta.EvaluationService.CreateEvaluation]. + + Attributes: + parent (str): + Required. The app to create the evaluation for. Format: + ``projects/{project}/locations/{location}/apps/{app}`` + evaluation_id (str): + Optional. The ID to use for the evaluation, + which will become the final component of the + evaluation's resource name. If not provided, a + unique ID will be automatically assigned for the + evaluation. + evaluation (google.cloud.ces_v1beta.types.Evaluation): + Required. The evaluation to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + evaluation_id: str = proto.Field( + proto.STRING, + number=2, + ) + evaluation: gcc_evaluation.Evaluation = proto.Field( + proto.MESSAGE, + number=3, + message=gcc_evaluation.Evaluation, + ) + + +class GenerateEvaluationRequest(proto.Message): + r"""Request message for + [EvaluationService.GenerateEvaluation][google.cloud.ces.v1beta.EvaluationService.GenerateEvaluation]. + + Attributes: + conversation (str): + Required. The conversation to create the golden evaluation + for. Format: + ``projects/{project}/locations/{location}/apps/{app}/conversations/{conversation}`` + source (google.cloud.ces_v1beta.types.Conversation.Source): + Optional. Indicate the source of the + conversation. If not set, all sources will be + searched. + """ + + conversation: str = proto.Field( + proto.STRING, + number=1, + ) + source: gcc_conversation.Conversation.Source = proto.Field( + proto.ENUM, + number=2, + enum=gcc_conversation.Conversation.Source, + ) + + +class ImportEvaluationsRequest(proto.Message): + r"""Request message for + [EvaluationService.ImportEvaluations][google.cloud.ces.v1beta.EvaluationService.ImportEvaluations]. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + conversation_list (google.cloud.ces_v1beta.types.ImportEvaluationsRequest.ConversationList): + The conversations to import the evaluations + from. + + This field is a member of `oneof`_ ``source``. + gcs_uri (str): + The `Google Cloud + Storage `__ URI from + which to import evaluations. The format of this URI must be + ``gs:///``. + + This field is a member of `oneof`_ ``source``. + csv_content (bytes): + Raw bytes representing the csv file with the + evaluations structure. + + This field is a member of `oneof`_ ``source``. + parent (str): + Required. The app to import the evaluations into. Format: + ``projects/{project}/locations/{location}/apps/{app}`` + import_options (google.cloud.ces_v1beta.types.ImportEvaluationsRequest.ImportOptions): + Optional. Options governing the import + process for the evaluations. + """ + + class ConversationList(proto.Message): + r"""A list of conversation resource names. + + Attributes: + conversations (MutableSequence[str]): + Optional. Conversation resource names. + """ + + conversations: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class ImportOptions(proto.Message): + r"""Configuration options for the evaluation import process. + These options control how the import behaves, particularly when + conflicts arise with existing evaluations data. + + Attributes: + conflict_resolution_strategy (google.cloud.ces_v1beta.types.ImportEvaluationsRequest.ImportOptions.ConflictResolutionStrategy): + Optional. The strategy to use when resolving + conflicts during import. + """ + + class ConflictResolutionStrategy(proto.Enum): + r"""Defines the strategy for handling conflicts when an + evaluation with the same evaluation ID already exists in the + app. + + Values: + CONFLICT_RESOLUTION_STRATEGY_UNSPECIFIED (0): + The conflict resolution strategy is + unspecified. + OVERWRITE (1): + Overwrite the existing evaluation with the + new one. + SKIP (2): + Keep the existing evaluation and skip the new + one. + DUPLICATE (3): + Keep the existing evaluation and duplicate + the new one as a new evaluation. + """ + + CONFLICT_RESOLUTION_STRATEGY_UNSPECIFIED = 0 + OVERWRITE = 1 + SKIP = 2 + DUPLICATE = 3 + + conflict_resolution_strategy: "ImportEvaluationsRequest.ImportOptions.ConflictResolutionStrategy" = proto.Field( + proto.ENUM, + number=1, + enum="ImportEvaluationsRequest.ImportOptions.ConflictResolutionStrategy", + ) + + conversation_list: ConversationList = proto.Field( + proto.MESSAGE, + number=2, + oneof="source", + message=ConversationList, + ) + gcs_uri: str = proto.Field( + proto.STRING, + number=3, + oneof="source", + ) + csv_content: bytes = proto.Field( + proto.BYTES, + number=4, + oneof="source", + ) + parent: str = proto.Field( + proto.STRING, + number=1, + ) + import_options: ImportOptions = proto.Field( + proto.MESSAGE, + number=5, + message=ImportOptions, + ) + + +class ImportEvaluationsResponse(proto.Message): + r"""Response message for + [EvaluationService.ImportEvaluations][google.cloud.ces.v1beta.EvaluationService.ImportEvaluations]. + + Attributes: + evaluations (MutableSequence[google.cloud.ces_v1beta.types.Evaluation]): + The list of evaluations that were imported + into the app. + error_messages (MutableSequence[str]): + Optional. A list of error messages associated + with evaluations that failed to be imported. + import_failure_count (int): + The number of evaluations that were not + imported due to errors. + """ + + evaluations: MutableSequence[gcc_evaluation.Evaluation] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcc_evaluation.Evaluation, + ) + error_messages: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + import_failure_count: int = proto.Field( + proto.INT32, + number=3, + ) + + +class ImportEvaluationsOperationMetadata(proto.Message): + r"""Represents the metadata of the long-running operation for + [EvaluationService.ImportEvaluations][google.cloud.ces.v1beta.EvaluationService.ImportEvaluations]. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation was + created. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation finished + running. + status_message (str): + Output only. Human-readable status of the + operation, if any. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + status_message: str = proto.Field( + proto.STRING, + number=3, + ) + + +class CreateEvaluationDatasetRequest(proto.Message): + r"""Request message for + [EvaluationService.CreateEvaluationDataset][google.cloud.ces.v1beta.EvaluationService.CreateEvaluationDataset]. + + Attributes: + parent (str): + Required. The app to create the evaluation for. Format: + ``projects/{project}/locations/{location}/apps/{app}`` + evaluation_dataset_id (str): + Optional. The ID to use for the evaluation + dataset, which will become the final component + of the evaluation dataset's resource name. If + not provided, a unique ID will be automatically + assigned for the evaluation. + evaluation_dataset (google.cloud.ces_v1beta.types.EvaluationDataset): + Required. The evaluation dataset to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + evaluation_dataset_id: str = proto.Field( + proto.STRING, + number=2, + ) + evaluation_dataset: gcc_evaluation.EvaluationDataset = proto.Field( + proto.MESSAGE, + number=3, + message=gcc_evaluation.EvaluationDataset, + ) + + +class UpdateEvaluationRequest(proto.Message): + r"""Request message for + [EvaluationService.UpdateEvaluation][google.cloud.ces.v1beta.EvaluationService.UpdateEvaluation]. + + Attributes: + evaluation (google.cloud.ces_v1beta.types.Evaluation): + Required. The evaluation to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to control which + fields get updated. If the mask is not present, + all fields will be updated. + """ + + evaluation: gcc_evaluation.Evaluation = proto.Field( + proto.MESSAGE, + number=1, + message=gcc_evaluation.Evaluation, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateEvaluationDatasetRequest(proto.Message): + r"""Request message for + [EvaluationService.UpdateEvaluationDataset][google.cloud.ces.v1beta.EvaluationService.UpdateEvaluationDataset]. + + Attributes: + evaluation_dataset (google.cloud.ces_v1beta.types.EvaluationDataset): + Required. The evaluation dataset to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to control which + fields get updated. If the mask is not present, + all fields will be updated. + """ + + evaluation_dataset: gcc_evaluation.EvaluationDataset = proto.Field( + proto.MESSAGE, + number=1, + message=gcc_evaluation.EvaluationDataset, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteEvaluationRequest(proto.Message): + r"""Request message for + [EvaluationService.DeleteEvaluation][google.cloud.ces.v1beta.EvaluationService.DeleteEvaluation]. + + Attributes: + name (str): + Required. The resource name of the evaluation + to delete. + force (bool): + Optional. Indicates whether to forcefully delete the + evaluation, even if it is still referenced by evaluation + datasets. + + - If ``force = false``, the deletion will fail if any + datasets still reference the evaluation. + - If ``force = true``, all existing references from datasets + will be removed and the evaluation will be deleted. + etag (str): + Optional. The current etag of the evaluation. + If an etag is not provided, the deletion will + overwrite any concurrent changes. If an etag is + provided and does not match the current etag of + the evaluation, deletion will be blocked and an + ABORTED error will be returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + force: bool = proto.Field( + proto.BOOL, + number=2, + ) + etag: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteEvaluationResultRequest(proto.Message): + r"""Request message for + [EvaluationService.DeleteEvaluationResult][google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationResult]. + + Attributes: + name (str): + Required. The resource name of the evaluation + result to delete. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteEvaluationDatasetRequest(proto.Message): + r"""Request message for + [EvaluationService.DeleteEvaluationDataset][google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationDataset]. + + Attributes: + name (str): + Required. The resource name of the evaluation + dataset to delete. + etag (str): + Optional. The current etag of the evaluation + dataset. If an etag is not provided, the + deletion will overwrite any concurrent changes. + If an etag is provided and does not match the + current etag of the evaluation dataset, deletion + will be blocked and an ABORTED error will be + returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + etag: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteEvaluationRunRequest(proto.Message): + r"""Request message for + [EvaluationService.DeleteEvaluationRun][google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationRun]. + + Attributes: + name (str): + Required. The resource name of the evaluation + run to delete. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetEvaluationRequest(proto.Message): + r"""Request message for + [EvaluationService.GetEvaluation][google.cloud.ces.v1beta.EvaluationService.GetEvaluation]. + + Attributes: + name (str): + Required. The resource name of the evaluation + to retrieve. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetEvaluationResultRequest(proto.Message): + r"""Request message for + [EvaluationService.GetEvaluationResult][google.cloud.ces.v1beta.EvaluationService.GetEvaluationResult]. + + Attributes: + name (str): + Required. The resource name of the evaluation + result to retrieve. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetEvaluationDatasetRequest(proto.Message): + r"""Request message for + [EvaluationService.GetEvaluationDataset][google.cloud.ces.v1beta.EvaluationService.GetEvaluationDataset]. + + Attributes: + name (str): + Required. The resource name of the evaluation + dataset to retrieve. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetEvaluationRunRequest(proto.Message): + r"""Request message for + [EvaluationService.GetEvaluationRun][google.cloud.ces.v1beta.EvaluationService.GetEvaluationRun]. + + Attributes: + name (str): + Required. The resource name of the evaluation + run to retrieve. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListEvaluationsRequest(proto.Message): + r"""Request message for + [EvaluationService.ListEvaluations][google.cloud.ces.v1beta.EvaluationService.ListEvaluations]. + + Attributes: + parent (str): + Required. The resource name of the app to + list evaluations from. + page_size (int): + Optional. Requested page size. Server may + return fewer items than requested. If + unspecified, server will pick an appropriate + default. + page_token (str): + Optional. The + [next_page_token][google.cloud.ces.v1beta.ListEvaluationsResponse.next_page_token] + value returned from a previous list + [EvaluationService.ListEvaluations][google.cloud.ces.v1beta.EvaluationService.ListEvaluations] + call. + filter (str): + Optional. Deprecated: Use evaluation_filter and + evaluation_run_filter instead. + evaluation_filter (str): + Optional. Filter to be applied on the evaluation when + listing the evaluations. See https://google.aip.dev/160 for + more details. Supported fields: evaluation_datasets + evaluation_run_filter (str): + Optional. Filter string for fields on the associated + EvaluationRun resources. See https://google.aip.dev/160 for + more details. Supported fields: create_time, initiated_by, + app_version_display_name + order_by (str): + Optional. Field to sort by. Only "name" and "create_time", + and "update_time" are supported. Time fields are ordered in + descending order, and the name field is ordered in ascending + order. If not included, "update_time" will be the default. + See https://google.aip.dev/132#ordering for more details. + last_ten_results (bool): + Optional. Whether to include the last 10 + evaluation results for each evaluation in the + response. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + evaluation_filter: str = proto.Field( + proto.STRING, + number=7, + ) + evaluation_run_filter: str = proto.Field( + proto.STRING, + number=8, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + last_ten_results: bool = proto.Field( + proto.BOOL, + number=6, + ) + + +class ListEvaluationResultsRequest(proto.Message): + r"""Request message for + [EvaluationService.ListEvaluationResults][google.cloud.ces.v1beta.EvaluationService.ListEvaluationResults]. + + Attributes: + parent (str): + Required. The resource name of the evaluation to list + evaluation results from. To filter by evaluation run, use + ``-`` as the evaluation ID and specify the evaluation run ID + in the filter. For example: + ``projects/{project}/locations/{location}/apps/{app}/evaluations/-`` + page_size (int): + Optional. Requested page size. Server may + return fewer items than requested. If + unspecified, server will pick an appropriate + default. + page_token (str): + Optional. The + [next_page_token][google.cloud.ces.v1beta.ListEvaluationResultsResponse.next_page_token] + value returned from a previous list + [EvaluationService.ListEvaluationResults][google.cloud.ces.v1beta.EvaluationService.ListEvaluationResults] + call. + filter (str): + Optional. Filter to be applied when listing + the evaluation results. See + https://google.aip.dev/160 for more details. + order_by (str): + Optional. Field to sort by. Only "name" and "create_time", + and "update_time" are supported. Time fields are ordered in + descending order, and the name field is ordered in ascending + order. If not included, "update_time" will be the default. + See https://google.aip.dev/132#ordering for more details. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListEvaluationDatasetsRequest(proto.Message): + r"""Request message for + [EvaluationService.ListEvaluationDatasets][google.cloud.ces.v1beta.EvaluationService.ListEvaluationDatasets]. + + Attributes: + parent (str): + Required. The resource name of the app to + list evaluation datasets from. + page_size (int): + Optional. Requested page size. Server may + return fewer items than requested. If + unspecified, server will pick an appropriate + default. + page_token (str): + Optional. The + [next_page_token][google.cloud.ces.v1beta.ListEvaluationDatasetsResponse.next_page_token] + value returned from a previous list + [EvaluationService.ListEvaluationDatasets][google.cloud.ces.v1beta.EvaluationService.ListEvaluationDatasets] + call. + filter (str): + Optional. Filter to be applied when listing + the evaluation datasets. See + https://google.aip.dev/160 for more details. + order_by (str): + Optional. Field to sort by. Only "name" and "create_time", + and "update_time" are supported. Time fields are ordered in + descending order, and the name field is ordered in ascending + order. If not included, "update_time" will be the default. + See https://google.aip.dev/132#ordering for more details. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListEvaluationRunsRequest(proto.Message): + r"""Request message for + [EvaluationService.ListEvaluationRuns][google.cloud.ces.v1beta.EvaluationService.ListEvaluationRuns]. + + Attributes: + parent (str): + Required. The resource name of the app to + list evaluation runs from. + page_size (int): + Optional. Requested page size. Server may + return fewer items than requested. If + unspecified, server will pick an appropriate + default. + page_token (str): + Optional. The + [next_page_token][google.cloud.ces.v1beta.ListEvaluationRunsResponse.next_page_token] + value returned from a previous list + [EvaluationService.ListEvaluationRuns][google.cloud.ces.v1beta.EvaluationService.ListEvaluationRuns] + call. + filter (str): + Optional. Filter to be applied when listing + the evaluation runs. See + https://google.aip.dev/160 for more details. + order_by (str): + Optional. Field to sort by. Only "name" and "create_time", + and "update_time" are supported. Time fields are ordered in + descending order, and the name field is ordered in ascending + order. If not included, "update_time" will be the default. + See https://google.aip.dev/132#ordering for more details. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListEvaluationsResponse(proto.Message): + r"""Response message for + [EvaluationService.ListEvaluations][google.cloud.ces.v1beta.EvaluationService.ListEvaluations]. + + Attributes: + evaluations (MutableSequence[google.cloud.ces_v1beta.types.Evaluation]): + The list of evaluations. + next_page_token (str): + A token that can be sent as + [ListEvaluationsRequest.page_token][google.cloud.ces.v1beta.ListEvaluationsRequest.page_token] + to retrieve the next page. Absence of this field indicates + there are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + evaluations: MutableSequence[gcc_evaluation.Evaluation] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcc_evaluation.Evaluation, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListEvaluationResultsResponse(proto.Message): + r"""Response message for + [EvaluationService.ListEvaluationResults][google.cloud.ces.v1beta.EvaluationService.ListEvaluationResults]. + + Attributes: + evaluation_results (MutableSequence[google.cloud.ces_v1beta.types.EvaluationResult]): + The list of evaluation results. + next_page_token (str): + A token that can be sent as + [ListEvaluationResultsRequest.page_token][google.cloud.ces.v1beta.ListEvaluationResultsRequest.page_token] + to retrieve the next page. Absence of this field indicates + there are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + evaluation_results: MutableSequence[gcc_evaluation.EvaluationResult] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcc_evaluation.EvaluationResult, + ) + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListEvaluationDatasetsResponse(proto.Message): + r"""Response message for + [EvaluationService.ListEvaluationDatasets][google.cloud.ces.v1beta.EvaluationService.ListEvaluationDatasets]. + + Attributes: + evaluation_datasets (MutableSequence[google.cloud.ces_v1beta.types.EvaluationDataset]): + The list of evaluation datasets. + next_page_token (str): + A token that can be sent as + [ListEvaluationDatasetsRequest.page_token][google.cloud.ces.v1beta.ListEvaluationDatasetsRequest.page_token] + to retrieve the next page. Absence of this field indicates + there are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + evaluation_datasets: MutableSequence[gcc_evaluation.EvaluationDataset] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcc_evaluation.EvaluationDataset, + ) + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListEvaluationRunsResponse(proto.Message): + r"""Response message for + [EvaluationService.ListEvaluationRuns][google.cloud.ces.v1beta.EvaluationService.ListEvaluationRuns]. + + Attributes: + evaluation_runs (MutableSequence[google.cloud.ces_v1beta.types.EvaluationRun]): + The list of evaluation runs. + next_page_token (str): + A token that can be sent as + [ListEvaluationRunsRequest.page_token][google.cloud.ces.v1beta.ListEvaluationRunsRequest.page_token] + to retrieve the next page. Absence of this field indicates + there are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + evaluation_runs: MutableSequence[gcc_evaluation.EvaluationRun] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcc_evaluation.EvaluationRun, + ) + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CreateScheduledEvaluationRunRequest(proto.Message): + r"""Request message for + [EvaluationService.CreateScheduledEvaluationRun][google.cloud.ces.v1beta.EvaluationService.CreateScheduledEvaluationRun]. + + Attributes: + parent (str): + Required. The app to create the scheduled evaluation run + for. Format: + ``projects/{project}/locations/{location}/apps/{app}`` + scheduled_evaluation_run_id (str): + Optional. The ID to use for the scheduled + evaluation run, which will become the final + component of the scheduled evaluation run's + resource name. If not provided, a unique ID will + be automatically assigned. + scheduled_evaluation_run (google.cloud.ces_v1beta.types.ScheduledEvaluationRun): + Required. The scheduled evaluation run to + create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + scheduled_evaluation_run_id: str = proto.Field( + proto.STRING, + number=2, + ) + scheduled_evaluation_run: gcc_evaluation.ScheduledEvaluationRun = proto.Field( + proto.MESSAGE, + number=3, + message=gcc_evaluation.ScheduledEvaluationRun, + ) + + +class GetScheduledEvaluationRunRequest(proto.Message): + r"""Request message for + [EvaluationService.GetScheduledEvaluationRun][google.cloud.ces.v1beta.EvaluationService.GetScheduledEvaluationRun]. + + Attributes: + name (str): + Required. The resource name of the scheduled + evaluation run to retrieve. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListScheduledEvaluationRunsRequest(proto.Message): + r"""Request message for + [EvaluationService.ListScheduledEvaluationRuns][google.cloud.ces.v1beta.EvaluationService.ListScheduledEvaluationRuns]. + + Attributes: + parent (str): + Required. The resource name of the app to + list scheduled evaluation runs from. + page_size (int): + Optional. Requested page size. Server may + return fewer items than requested. If + unspecified, server will pick an appropriate + default. + page_token (str): + Optional. The + [next_page_token][google.cloud.ces.v1beta.ListScheduledEvaluationRunsResponse.next_page_token] + value returned from a previous list + [EvaluationService.ListScheduledEvaluationRuns][google.cloud.ces.v1beta.EvaluationService.ListScheduledEvaluationRuns] + call. + filter (str): + Optional. Filter to be applied when listing the scheduled + evaluation runs. See https://google.aip.dev/160 for more + details. Currently supports filtering by: + + - request.evaluations:evaluation_id + - request.evaluation_dataset:evaluation_dataset_id + order_by (str): + Optional. Field to sort by. Supported fields are: "name" + (ascending), "create_time" (descending), "update_time" + (descending), "next_scheduled_execution" (ascending), and + "last_completed_run.create_time" (descending). If not + included, "update_time" will be the default. See + https://google.aip.dev/132#ordering for more details. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListScheduledEvaluationRunsResponse(proto.Message): + r"""Response message for + [EvaluationService.ListScheduledEvaluationRuns][google.cloud.ces.v1beta.EvaluationService.ListScheduledEvaluationRuns]. + + Attributes: + scheduled_evaluation_runs (MutableSequence[google.cloud.ces_v1beta.types.ScheduledEvaluationRun]): + The list of scheduled evaluation runs. + next_page_token (str): + A token that can be sent as + [ListScheduledEvaluationRunsRequest.page_token][google.cloud.ces.v1beta.ListScheduledEvaluationRunsRequest.page_token] + to retrieve the next page. Absence of this field indicates + there are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + scheduled_evaluation_runs: MutableSequence[ + gcc_evaluation.ScheduledEvaluationRun + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcc_evaluation.ScheduledEvaluationRun, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class UpdateScheduledEvaluationRunRequest(proto.Message): + r"""Request message for + [EvaluationService.UpdateScheduledEvaluationRun][google.cloud.ces.v1beta.EvaluationService.UpdateScheduledEvaluationRun]. + + Attributes: + scheduled_evaluation_run (google.cloud.ces_v1beta.types.ScheduledEvaluationRun): + Required. The scheduled evaluation run to + update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to control which + fields get updated. If the mask is not present, + all fields will be updated. + """ + + scheduled_evaluation_run: gcc_evaluation.ScheduledEvaluationRun = proto.Field( + proto.MESSAGE, + number=1, + message=gcc_evaluation.ScheduledEvaluationRun, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteScheduledEvaluationRunRequest(proto.Message): + r"""Request message for + [EvaluationService.DeleteScheduledEvaluationRun][google.cloud.ces.v1beta.EvaluationService.DeleteScheduledEvaluationRun]. + + Attributes: + name (str): + Required. The resource name of the scheduled + evaluation run to delete. + etag (str): + Optional. The etag of the + ScheduledEvaluationRun. If provided, it must + match the server's etag. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + etag: str = proto.Field( + proto.STRING, + number=2, + ) + + +class TestPersonaVoiceRequest(proto.Message): + r"""Request message for + [EvaluationService.TestPersonaVoice][google.cloud.ces.v1beta.EvaluationService.TestPersonaVoice]. + + Attributes: + app (str): + Required. the resource name of the app to test the persona + voice for. Format: + ``projects/{project}/locations/{location}/apps/{app}`` + persona_id (str): + Required. The persona ID to test the voice + for. Also accepts "default". + text (str): + Required. The text to test the voice for. + """ + + app: str = proto.Field( + proto.STRING, + number=1, + ) + persona_id: str = proto.Field( + proto.STRING, + number=2, + ) + text: str = proto.Field( + proto.STRING, + number=3, + ) + + +class UploadEvaluationAudioRequest(proto.Message): + r"""Request message for + [EvaluationService.UploadEvaluationAudio][google.cloud.ces.v1beta.EvaluationService.UploadEvaluationAudio]. + + Attributes: + app (str): + Required. The resource name of the App for which to upload + the evaluation audio. Format: + ``projects/{project}/locations/{location}/apps/{app}`` + audio_content (bytes): + Required. The raw audio bytes. + The format of the audio must be single-channel + LINEAR16 with a sample rate of 16kHz (default + InputAudioConfig). + """ + + app: str = proto.Field( + proto.STRING, + number=1, + ) + audio_content: bytes = proto.Field( + proto.BYTES, + number=2, + ) + + +class UploadEvaluationAudioResponse(proto.Message): + r"""Response message for + [EvaluationService.UploadEvaluationAudio][google.cloud.ces.v1beta.EvaluationService.UploadEvaluationAudio]. + + Attributes: + audio_gcs_uri (str): + The Google Cloud Storage URI where the uploaded audio file + is stored. Format: ``gs:///`` + audio_transcript (str): + The transcribed text from the audio, + generated by Cloud Speech-to-Text. + audio_duration (google.protobuf.duration_pb2.Duration): + The duration of the audio. + """ + + audio_gcs_uri: str = proto.Field( + proto.STRING, + number=1, + ) + audio_transcript: str = proto.Field( + proto.STRING, + number=2, + ) + audio_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + + +class TestPersonaVoiceResponse(proto.Message): + r"""Response message for + [EvaluationService.TestPersonaVoice][google.cloud.ces.v1beta.EvaluationService.TestPersonaVoice]. + + Attributes: + audio (bytes): + The audio data bytes of the synthesized + voice. + """ + + audio: bytes = proto.Field( + proto.BYTES, + number=1, + ) + + +class CreateEvaluationExpectationRequest(proto.Message): + r"""Request message for + [EvaluationService.CreateEvaluationExpectation][google.cloud.ces.v1beta.EvaluationService.CreateEvaluationExpectation]. + + Attributes: + parent (str): + Required. The app to create the evaluation expectation for. + Format: + ``projects/{project}/locations/{location}/apps/{app}`` + evaluation_expectation_id (str): + Optional. The ID to use for the evaluation + expectation, which will become the final + component of the evaluation expectation's + resource name. If not provided, a unique ID will + be automatically assigned for the evaluation + expectation. + evaluation_expectation (google.cloud.ces_v1beta.types.EvaluationExpectation): + Required. The evaluation expectation to + create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + evaluation_expectation_id: str = proto.Field( + proto.STRING, + number=2, + ) + evaluation_expectation: gcc_evaluation.EvaluationExpectation = proto.Field( + proto.MESSAGE, + number=3, + message=gcc_evaluation.EvaluationExpectation, + ) + + +class UpdateEvaluationExpectationRequest(proto.Message): + r"""Request message for + [EvaluationService.UpdateEvaluationExpectation][google.cloud.ces.v1beta.EvaluationService.UpdateEvaluationExpectation]. + + Attributes: + evaluation_expectation (google.cloud.ces_v1beta.types.EvaluationExpectation): + Required. The evaluation expectation to + update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to control which + fields get updated. If the mask is not present, + all fields will be updated. + """ + + evaluation_expectation: gcc_evaluation.EvaluationExpectation = proto.Field( + proto.MESSAGE, + number=1, + message=gcc_evaluation.EvaluationExpectation, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class DeleteEvaluationExpectationRequest(proto.Message): + r"""Request message for + [EvaluationService.DeleteEvaluationExpectation][google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationExpectation]. + + Attributes: + name (str): + Required. The resource name of the evaluation + expectation to delete. + etag (str): + Optional. The current etag of the evaluation + expectation. If an etag is not provided, the + deletion will overwrite any concurrent changes. + If an etag is provided and does not match the + current etag of the evaluation expectation, + deletion will be blocked and an ABORTED error + will be returned. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + etag: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetEvaluationExpectationRequest(proto.Message): + r"""Request message for + [EvaluationService.GetEvaluationExpectation][google.cloud.ces.v1beta.EvaluationService.GetEvaluationExpectation]. + + Attributes: + name (str): + Required. The resource name of the evaluation + expectation to retrieve. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListEvaluationExpectationsRequest(proto.Message): + r"""Request message for + [EvaluationService.ListEvaluationExpectations][google.cloud.ces.v1beta.EvaluationService.ListEvaluationExpectations]. + + Attributes: + parent (str): + Required. The resource name of the app to + list evaluation expectations from. + page_size (int): + Optional. Requested page size. Server may + return fewer items than requested. If + unspecified, server will pick an appropriate + default. + page_token (str): + Optional. The + [next_page_token][google.cloud.ces.v1beta.ListEvaluationExpectationsResponse.next_page_token] + value returned from a previous list + [EvaluationService.ListEvaluationExpectations][google.cloud.ces.v1beta.EvaluationService.ListEvaluationExpectations] + call. + filter (str): + Optional. Filter to be applied when listing + the evaluation expectations. See + https://google.aip.dev/160 for more details. + order_by (str): + Optional. Field to sort by. Only "name" and "create_time", + and "update_time" are supported. Time fields are ordered in + descending order, and the name field is ordered in ascending + order. If not included, "update_time" will be the default. + See https://google.aip.dev/132#ordering for more details. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListEvaluationExpectationsResponse(proto.Message): + r"""Response message for + [EvaluationService.ListEvaluationExpectations][google.cloud.ces.v1beta.EvaluationService.ListEvaluationExpectations]. + + Attributes: + evaluation_expectations (MutableSequence[google.cloud.ces_v1beta.types.EvaluationExpectation]): + The list of evaluation expectations. + next_page_token (str): + A token that can be sent as + [ListEvaluationExpectationsRequest.page_token][google.cloud.ces.v1beta.ListEvaluationExpectationsRequest.page_token] + to retrieve the next page. Absence of this field indicates + there are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + evaluation_expectations: MutableSequence[gcc_evaluation.EvaluationExpectation] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcc_evaluation.EvaluationExpectation, + ) + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/example.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/example.py new file mode 100644 index 000000000000..794f799f62d1 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/example.py @@ -0,0 +1,460 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import google.protobuf.struct_pb2 as struct_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.ces_v1beta.types import toolset_tool as gcc_toolset_tool + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "Example", + "Message", + "Chunk", + "Blob", + "Image", + "ToolCall", + "ToolResponse", + "AgentTransfer", + }, +) + + +class Example(proto.Message): + r"""An example represents a sample conversation between the user + and the agent(s). + + Attributes: + name (str): + Identifier. The unique identifier of the example. Format: + ``projects/{project}/locations/{location}/apps/{app}/examples/{example}`` + display_name (str): + Required. Display name of the example. + description (str): + Optional. Human-readable description of the + example. + entry_agent (str): + Optional. The agent that initially handles the conversation. + If not specified, the example represents a conversation that + is handled by the root agent. Format: + ``projects/{project}/locations/{location}/apps/{app}/agents/{agent}`` + messages (MutableSequence[google.cloud.ces_v1beta.types.Message]): + Optional. The collection of messages that + make up the conversation. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the example was + created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the example was + last updated. + invalid (bool): + Output only. The example may become invalid + if referencing resources are deleted. Invalid + examples will not be used as few-shot examples. + etag (str): + Etag used to ensure the object hasn't changed + during a read-modify-write operation. If the + etag is empty, the update will overwrite any + concurrent changes. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + entry_agent: str = proto.Field( + proto.STRING, + number=4, + ) + messages: MutableSequence["Message"] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message="Message", + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + invalid: bool = proto.Field( + proto.BOOL, + number=8, + ) + etag: str = proto.Field( + proto.STRING, + number=9, + ) + + +class Message(proto.Message): + r"""A message within a conversation. + + Attributes: + role (str): + Optional. The role within the conversation, + e.g., user, agent. + chunks (MutableSequence[google.cloud.ces_v1beta.types.Chunk]): + Optional. Content of the message as a series + of chunks. + event_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. Timestamp when the message was sent or received. + Should not be used if the message is part of an + [example][google.cloud.ces.v1beta.Example]. + """ + + role: str = proto.Field( + proto.STRING, + number=1, + ) + chunks: MutableSequence["Chunk"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="Chunk", + ) + event_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + +class Chunk(proto.Message): + r"""A chunk of content within a message. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + text (str): + Optional. Text data. + + This field is a member of `oneof`_ ``data``. + transcript (str): + Optional. Transcript associated with the + audio. + + This field is a member of `oneof`_ ``data``. + blob (google.cloud.ces_v1beta.types.Blob): + Optional. Blob data. + + This field is a member of `oneof`_ ``data``. + payload (google.protobuf.struct_pb2.Struct): + Optional. Custom payload data. + + This field is a member of `oneof`_ ``data``. + image (google.cloud.ces_v1beta.types.Image): + Optional. Image data. + + This field is a member of `oneof`_ ``data``. + tool_call (google.cloud.ces_v1beta.types.ToolCall): + Optional. Tool execution request. + + This field is a member of `oneof`_ ``data``. + tool_response (google.cloud.ces_v1beta.types.ToolResponse): + Optional. Tool execution response. + + This field is a member of `oneof`_ ``data``. + agent_transfer (google.cloud.ces_v1beta.types.AgentTransfer): + Optional. Agent transfer event. + + This field is a member of `oneof`_ ``data``. + updated_variables (google.protobuf.struct_pb2.Struct): + A struct represents variables that were + updated in the conversation, keyed by variable + names. + + This field is a member of `oneof`_ ``data``. + default_variables (google.protobuf.struct_pb2.Struct): + A struct represents default variables at the + start of the conversation, keyed by variable + names. + + This field is a member of `oneof`_ ``data``. + """ + + text: str = proto.Field( + proto.STRING, + number=1, + oneof="data", + ) + transcript: str = proto.Field( + proto.STRING, + number=9, + oneof="data", + ) + blob: "Blob" = proto.Field( + proto.MESSAGE, + number=7, + oneof="data", + message="Blob", + ) + payload: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=11, + oneof="data", + message=struct_pb2.Struct, + ) + image: "Image" = proto.Field( + proto.MESSAGE, + number=5, + oneof="data", + message="Image", + ) + tool_call: "ToolCall" = proto.Field( + proto.MESSAGE, + number=2, + oneof="data", + message="ToolCall", + ) + tool_response: "ToolResponse" = proto.Field( + proto.MESSAGE, + number=3, + oneof="data", + message="ToolResponse", + ) + agent_transfer: "AgentTransfer" = proto.Field( + proto.MESSAGE, + number=4, + oneof="data", + message="AgentTransfer", + ) + updated_variables: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=8, + oneof="data", + message=struct_pb2.Struct, + ) + default_variables: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=10, + oneof="data", + message=struct_pb2.Struct, + ) + + +class Blob(proto.Message): + r"""Represents a blob input or output in the conversation. + + Attributes: + mime_type (str): + Required. The IANA standard MIME type of the + source data. + data (bytes): + Required. Raw bytes of the blob. + """ + + mime_type: str = proto.Field( + proto.STRING, + number=1, + ) + data: bytes = proto.Field( + proto.BYTES, + number=2, + ) + + +class Image(proto.Message): + r"""Represents an image input or output in the conversation. + + Attributes: + mime_type (str): + Required. The IANA standard MIME type of the source data. + Supported image types includes: + + - image/png + - image/jpeg + - image/webp + data (bytes): + Required. Raw bytes of the image. + """ + + mime_type: str = proto.Field( + proto.STRING, + number=1, + ) + data: bytes = proto.Field( + proto.BYTES, + number=2, + ) + + +class ToolCall(proto.Message): + r"""Request for the client or the agent to execute the specified + tool. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + tool (str): + Optional. The name of the tool to execute. Format: + ``projects/{project}/locations/{location}/apps/{app}/tools/{tool}`` + + This field is a member of `oneof`_ ``tool_identifier``. + toolset_tool (google.cloud.ces_v1beta.types.ToolsetTool): + Optional. The toolset tool to execute. + + This field is a member of `oneof`_ ``tool_identifier``. + id (str): + Optional. The unique identifier of the tool call. If + populated, the client should return the execution result + with the matching ID in + [ToolResponse][google.cloud.ces.v1beta.ToolResponse.id]. + display_name (str): + Output only. Display name of the tool. + args (google.protobuf.struct_pb2.Struct): + Optional. The input parameters and values for + the tool in JSON object format. + """ + + tool: str = proto.Field( + proto.STRING, + number=2, + oneof="tool_identifier", + ) + toolset_tool: gcc_toolset_tool.ToolsetTool = proto.Field( + proto.MESSAGE, + number=5, + oneof="tool_identifier", + message=gcc_toolset_tool.ToolsetTool, + ) + id: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=4, + ) + args: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=3, + message=struct_pb2.Struct, + ) + + +class ToolResponse(proto.Message): + r"""The execution result of a specific tool from the client or + the agent. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + tool (str): + Optional. The name of the tool to execute. Format: + ``projects/{project}/locations/{location}/apps/{app}/tools/{tool}`` + + This field is a member of `oneof`_ ``tool_identifier``. + toolset_tool (google.cloud.ces_v1beta.types.ToolsetTool): + Optional. The toolset tool that got executed. + + This field is a member of `oneof`_ ``tool_identifier``. + id (str): + Optional. The matching ID of the [tool + call][google.cloud.ces.v1beta.ToolCall] the response is for. + display_name (str): + Output only. Display name of the tool. + response (google.protobuf.struct_pb2.Struct): + Required. The tool execution result in JSON + object format. Use "output" key to specify tool + response and "error" key to specify error + details (if any). If "output" and "error" keys + are not specified, then whole "response" is + treated as tool execution result. + """ + + tool: str = proto.Field( + proto.STRING, + number=2, + oneof="tool_identifier", + ) + toolset_tool: gcc_toolset_tool.ToolsetTool = proto.Field( + proto.MESSAGE, + number=5, + oneof="tool_identifier", + message=gcc_toolset_tool.ToolsetTool, + ) + id: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=4, + ) + response: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=3, + message=struct_pb2.Struct, + ) + + +class AgentTransfer(proto.Message): + r"""Represents an event indicating the transfer of a conversation + to a different agent. + + Attributes: + target_agent (str): + Required. The agent to which the conversation is being + transferred. The agent will handle the conversation from + this point forward. Format: + ``projects/{project}/locations/{location}/apps/{app}/agents/{agent}`` + display_name (str): + Output only. Display name of the agent. + """ + + target_agent: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/fakes.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/fakes.py new file mode 100644 index 000000000000..0119df544c6e --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/fakes.py @@ -0,0 +1,100 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "EvaluationToolCallBehaviour", + "CodeBlock", + "ToolFakeConfig", + }, +) + + +class EvaluationToolCallBehaviour(proto.Enum): + r"""Configures the tool call behaviour for evaluation runs. + + Values: + EVALUATION_TOOL_CALL_BEHAVIOUR_UNSPECIFIED (0): + Unspecified tool call behavior. Will default + to real tool calls. + REAL (1): + Use real tool calls. + FAKE (2): + Use fake tool calls. + """ + + EVALUATION_TOOL_CALL_BEHAVIOUR_UNSPECIFIED = 0 + REAL = 1 + FAKE = 2 + + +class CodeBlock(proto.Message): + r"""A code block to be executed instead of a real tool call. + + Attributes: + python_code (str): + Required. Python code which will be invoked in tool fake + mode. Expected Python function signature - To catch all tool + calls: def fake_tool_call(tool: Tool, input: dict[str, Any], + callback_context: CallbackContext) -> Optional[dict[str, + Any]]: To catch a specific tool call: def + fake\_{tool_id}(tool: Tool, input: dict[str, Any], + callback_context: CallbackContext) -> Optional[dict[str, + Any]]: If the function returns None, the real tool will be + invoked instead. + """ + + python_code: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ToolFakeConfig(proto.Message): + r"""Configuration for tool behavior in fake mode. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + code_block (google.cloud.ces_v1beta.types.CodeBlock): + Optional. Code block which will be executed + instead of a real tool call. + + This field is a member of `oneof`_ ``tool_response``. + enable_fake_mode (bool): + Optional. Whether the tool is using fake + mode. + """ + + code_block: "CodeBlock" = proto.Field( + proto.MESSAGE, + number=1, + oneof="tool_response", + message="CodeBlock", + ) + enable_fake_mode: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/file_search_tool.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/file_search_tool.py new file mode 100644 index 000000000000..eba2fc5b055e --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/file_search_tool.py @@ -0,0 +1,83 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "FileSearchTool", + }, +) + + +class FileSearchTool(proto.Message): + r"""The file search tool allows the agent to search across the + files uploaded by the app/agent developer. It has presets to + give relatively good quality search over the uploaded files and + summarization of the retrieved results. + + Attributes: + corpus_type (google.cloud.ces_v1beta.types.FileSearchTool.CorpusType): + Optional. The type of the corpus. Default is FULLY_MANAGED. + name (str): + Required. The tool name. + description (str): + Optional. The tool description. + file_corpus (str): + Optional. The corpus where files are stored. Format: + projects/{project}/locations/{location}/ragCorpora/{rag_corpus} + """ + + class CorpusType(proto.Enum): + r"""The type of the Vertex RAG corpus. + + Values: + CORPUS_TYPE_UNSPECIFIED (0): + Unspecified corpus type. + USER_OWNED (1): + The corpus is created and owned by the user. + FULLY_MANAGED (2): + The corpus is created by the agent. + """ + + CORPUS_TYPE_UNSPECIFIED = 0 + USER_OWNED = 1 + FULLY_MANAGED = 2 + + corpus_type: CorpusType = proto.Field( + proto.ENUM, + number=3, + enum=CorpusType, + ) + name: str = proto.Field( + proto.STRING, + number=4, + ) + description: str = proto.Field( + proto.STRING, + number=5, + ) + file_corpus: str = proto.Field( + proto.STRING, + number=6, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/golden_run.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/golden_run.py new file mode 100644 index 000000000000..e498bac6051d --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/golden_run.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "GoldenRunMethod", + }, +) + + +class GoldenRunMethod(proto.Enum): + r"""The method used to run the evaluation. + + Values: + GOLDEN_RUN_METHOD_UNSPECIFIED (0): + Run method is not specified. + STABLE (1): + Run the evaluation as stable replay, where + each turn is a unique session with the previous + expected turns injected as context. + NAIVE (2): + Run the evaluation as naive replay, where the + run is a single session with no context + injected. + """ + + GOLDEN_RUN_METHOD_UNSPECIFIED = 0 + STABLE = 1 + NAIVE = 2 + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/google_search_tool.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/google_search_tool.py new file mode 100644 index 000000000000..8cc8c20d8129 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/google_search_tool.py @@ -0,0 +1,113 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "GoogleSearchTool", + }, +) + + +class GoogleSearchTool(proto.Message): + r"""Represents a tool to perform Google web searches for + grounding. See + https://cloud.google.com/customer-engagement-ai/conversational-agents/ps/tool#google-search. + + Attributes: + name (str): + Required. The name of the tool. + description (str): + Optional. Description of the tool's purpose. + context_urls (MutableSequence[str]): + Optional. Content will be fetched directly + from these URLs for context and grounding. + Example: "https://example.com/path.html". A + maximum of 20 URLs are allowed. + preferred_domains (MutableSequence[str]): + Optional. Specifies domains to restrict + search results to. Example: "example.com", + "another.site". A maximum of 20 domains can be + specified. + exclude_domains (MutableSequence[str]): + Optional. List of domains to be excluded from + the search results. Example: "example.com". + A maximum of 2000 domains can be excluded. + prompt_config (google.cloud.ces_v1beta.types.GoogleSearchTool.PromptConfig): + Optional. Prompt instructions passed to + planner on how the search results should be + processed for text and voice. + """ + + class PromptConfig(proto.Message): + r"""Prompt settings used by the model when processing or + summarizing the google search results. + + Attributes: + text_prompt (str): + Optional. Defines the prompt used for the + system instructions when interacting with the + agent in chat conversations. If not set, default + prompt will be used. + voice_prompt (str): + Optional. Defines the prompt used for the + system instructions when interacting with the + agent in voice conversations. If not set, + default prompt will be used. + """ + + text_prompt: str = proto.Field( + proto.STRING, + number=1, + ) + voice_prompt: str = proto.Field( + proto.STRING, + number=2, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + context_urls: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + preferred_domains: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + exclude_domains: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + prompt_config: PromptConfig = proto.Field( + proto.MESSAGE, + number=5, + message=PromptConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/guardrail.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/guardrail.py new file mode 100644 index 000000000000..febd30b92947 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/guardrail.py @@ -0,0 +1,546 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.ces_v1beta.types import common + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "Guardrail", + }, +) + + +class Guardrail(proto.Message): + r"""Guardrail contains a list of checks and balances to keep the + agents safe and secure. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + content_filter (google.cloud.ces_v1beta.types.Guardrail.ContentFilter): + Optional. Guardrail that bans certain content + from being used in the conversation. + + This field is a member of `oneof`_ ``guardrail_type``. + llm_prompt_security (google.cloud.ces_v1beta.types.Guardrail.LlmPromptSecurity): + Optional. Guardrail that blocks the + conversation if the prompt is considered unsafe + based on the LLM classification. + + This field is a member of `oneof`_ ``guardrail_type``. + llm_policy (google.cloud.ces_v1beta.types.Guardrail.LlmPolicy): + Optional. Guardrail that blocks the + conversation if the LLM response is considered + violating the policy based on the LLM + classification. + + This field is a member of `oneof`_ ``guardrail_type``. + model_safety (google.cloud.ces_v1beta.types.Guardrail.ModelSafety): + Optional. Guardrail that blocks the + conversation if the LLM response is considered + unsafe based on the model safety settings. + + This field is a member of `oneof`_ ``guardrail_type``. + code_callback (google.cloud.ces_v1beta.types.Guardrail.CodeCallback): + Optional. Guardrail that potentially blocks + the conversation based on the result of the + callback execution. + + This field is a member of `oneof`_ ``guardrail_type``. + name (str): + Identifier. The unique identifier of the guardrail. Format: + ``projects/{project}/locations/{location}/apps/{app}/guardrails/{guardrail}`` + display_name (str): + Required. Display name of the guardrail. + description (str): + Optional. Description of the guardrail. + enabled (bool): + Optional. Whether the guardrail is enabled. + action (google.cloud.ces_v1beta.types.TriggerAction): + Optional. Action to take when the guardrail + is triggered. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the guardrail was + created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the guardrail was + last updated. + etag (str): + Etag used to ensure the object hasn't changed + during a read-modify-write operation. If the + etag is empty, the update will overwrite any + concurrent changes. + """ + + class ContentFilter(proto.Message): + r"""Guardrail that bans certain content from being used in the + conversation. + + Attributes: + banned_contents (MutableSequence[str]): + Optional. List of banned phrases. Applies to + both user inputs and agent responses. + banned_contents_in_user_input (MutableSequence[str]): + Optional. List of banned phrases. Applies + only to user inputs. + banned_contents_in_agent_response (MutableSequence[str]): + Optional. List of banned phrases. Applies + only to agent responses. + match_type (google.cloud.ces_v1beta.types.Guardrail.ContentFilter.MatchType): + Required. Match type for the content filter. + disregard_diacritics (bool): + Optional. If true, diacritics are ignored + during matching. + """ + + class MatchType(proto.Enum): + r"""Match type for the content filter. + + Values: + MATCH_TYPE_UNSPECIFIED (0): + Match type is not specified. + SIMPLE_STRING_MATCH (1): + Content is matched for substrings character + by character. + WORD_BOUNDARY_STRING_MATCH (2): + Content only matches if the pattern found in + the text is surrounded by word delimiters. + Banned phrases can also contain word delimiters. + REGEXP_MATCH (3): + Content is matched using regular expression + syntax. + """ + + MATCH_TYPE_UNSPECIFIED = 0 + SIMPLE_STRING_MATCH = 1 + WORD_BOUNDARY_STRING_MATCH = 2 + REGEXP_MATCH = 3 + + banned_contents: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + banned_contents_in_user_input: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + banned_contents_in_agent_response: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + match_type: "Guardrail.ContentFilter.MatchType" = proto.Field( + proto.ENUM, + number=4, + enum="Guardrail.ContentFilter.MatchType", + ) + disregard_diacritics: bool = proto.Field( + proto.BOOL, + number=5, + ) + + class LlmPromptSecurity(proto.Message): + r"""Guardrail that blocks the conversation if the input is + considered unsafe based on the LLM classification. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + default_settings (google.cloud.ces_v1beta.types.Guardrail.LlmPromptSecurity.DefaultSecuritySettings): + Optional. Use the system's predefined default security + settings. To select this mode, include an empty + 'default_settings' message in the request. The + 'default_prompt_template' field within will be populated by + the server in the response. + + This field is a member of `oneof`_ ``security_config``. + custom_policy (google.cloud.ces_v1beta.types.Guardrail.LlmPolicy): + Optional. Use a user-defined LlmPolicy to + configure the security guardrail. + + This field is a member of `oneof`_ ``security_config``. + fail_open (bool): + Optional. Determines the behavior when the guardrail + encounters an LLM error. + + - If true: the guardrail is bypassed. + - If false (default): the guardrail triggers/blocks. + + Note: If a custom policy is provided, this field is ignored + in favor of the policy's 'fail_open' configuration. + """ + + class DefaultSecuritySettings(proto.Message): + r"""Configuration for default system security settings. + + Attributes: + default_prompt_template (str): + Output only. The default prompt template used by the system. + This field is for display purposes to show the user what + prompt the system uses by default. It is OUTPUT_ONLY. + """ + + default_prompt_template: str = proto.Field( + proto.STRING, + number=1, + ) + + default_settings: "Guardrail.LlmPromptSecurity.DefaultSecuritySettings" = ( + proto.Field( + proto.MESSAGE, + number=1, + oneof="security_config", + message="Guardrail.LlmPromptSecurity.DefaultSecuritySettings", + ) + ) + custom_policy: "Guardrail.LlmPolicy" = proto.Field( + proto.MESSAGE, + number=2, + oneof="security_config", + message="Guardrail.LlmPolicy", + ) + fail_open: bool = proto.Field( + proto.BOOL, + number=3, + ) + + class LlmPolicy(proto.Message): + r"""Guardrail that blocks the conversation if the LLM response is + considered violating the policy based on the LLM classification. + + Attributes: + max_conversation_messages (int): + Optional. When checking this policy, consider + the last 'n' messages in the conversation. When + not set a default value of 10 will be used. + model_settings (google.cloud.ces_v1beta.types.ModelSettings): + Optional. Model settings. + prompt (str): + Required. Policy prompt. + policy_scope (google.cloud.ces_v1beta.types.Guardrail.LlmPolicy.PolicyScope): + Required. Defines when to apply the policy check during the + conversation. If set to ``POLICY_SCOPE_UNSPECIFIED``, the + policy will be applied to the user input. When applying the + policy to the agent response, additional latency will be + introduced before the agent can respond. + fail_open (bool): + Optional. If an error occurs during the + policy check, fail open and do not trigger the + guardrail. + allow_short_utterance (bool): + Optional. By default, the LLM policy check is + bypassed for short utterances. Enabling this + setting applies the policy check to all + utterances, including those that would normally + be skipped. + """ + + class PolicyScope(proto.Enum): + r"""Defines when to apply the policy check during the + conversation. + + Values: + POLICY_SCOPE_UNSPECIFIED (0): + Policy scope is not specified. + USER_QUERY (1): + Policy check is triggered on user input. + AGENT_RESPONSE (2): + Policy check is triggered on agent response. + Applying this policy scope will introduce + additional latency before the agent can respond. + USER_QUERY_AND_AGENT_RESPONSE (3): + Policy check is triggered on both user input + and agent response. Applying this policy scope + will introduce additional latency before the + agent can respond. + """ + + POLICY_SCOPE_UNSPECIFIED = 0 + USER_QUERY = 1 + AGENT_RESPONSE = 2 + USER_QUERY_AND_AGENT_RESPONSE = 3 + + max_conversation_messages: int = proto.Field( + proto.INT32, + number=1, + ) + model_settings: common.ModelSettings = proto.Field( + proto.MESSAGE, + number=2, + message=common.ModelSettings, + ) + prompt: str = proto.Field( + proto.STRING, + number=3, + ) + policy_scope: "Guardrail.LlmPolicy.PolicyScope" = proto.Field( + proto.ENUM, + number=4, + enum="Guardrail.LlmPolicy.PolicyScope", + ) + fail_open: bool = proto.Field( + proto.BOOL, + number=5, + ) + allow_short_utterance: bool = proto.Field( + proto.BOOL, + number=6, + ) + + class ModelSafety(proto.Message): + r"""Model safety settings overrides. When this is set, it will + override the default settings and trigger the guardrail if the + response is considered unsafe. + + Attributes: + safety_settings (MutableSequence[google.cloud.ces_v1beta.types.Guardrail.ModelSafety.SafetySetting]): + Required. List of safety settings. + """ + + class HarmCategory(proto.Enum): + r"""Harm category. + + Values: + HARM_CATEGORY_UNSPECIFIED (0): + The harm category is unspecified. + HARM_CATEGORY_HATE_SPEECH (1): + The harm category is hate speech. + HARM_CATEGORY_DANGEROUS_CONTENT (2): + The harm category is dangerous content. + HARM_CATEGORY_HARASSMENT (3): + The harm category is harassment. + HARM_CATEGORY_SEXUALLY_EXPLICIT (4): + The harm category is sexually explicit + content. + """ + + HARM_CATEGORY_UNSPECIFIED = 0 + HARM_CATEGORY_HATE_SPEECH = 1 + HARM_CATEGORY_DANGEROUS_CONTENT = 2 + HARM_CATEGORY_HARASSMENT = 3 + HARM_CATEGORY_SEXUALLY_EXPLICIT = 4 + + class HarmBlockThreshold(proto.Enum): + r"""Probability based thresholds levels for blocking. + + Values: + HARM_BLOCK_THRESHOLD_UNSPECIFIED (0): + Unspecified harm block threshold. + BLOCK_LOW_AND_ABOVE (1): + Block low threshold and above (i.e. block + more). + BLOCK_MEDIUM_AND_ABOVE (2): + Block medium threshold and above. + BLOCK_ONLY_HIGH (3): + Block only high threshold (i.e. block less). + BLOCK_NONE (4): + Block none. + OFF (5): + Turn off the safety filter. + """ + + HARM_BLOCK_THRESHOLD_UNSPECIFIED = 0 + BLOCK_LOW_AND_ABOVE = 1 + BLOCK_MEDIUM_AND_ABOVE = 2 + BLOCK_ONLY_HIGH = 3 + BLOCK_NONE = 4 + OFF = 5 + + class SafetySetting(proto.Message): + r"""Safety setting. + + Attributes: + category (google.cloud.ces_v1beta.types.Guardrail.ModelSafety.HarmCategory): + Required. The harm category. + threshold (google.cloud.ces_v1beta.types.Guardrail.ModelSafety.HarmBlockThreshold): + Required. The harm block threshold. + """ + + category: "Guardrail.ModelSafety.HarmCategory" = proto.Field( + proto.ENUM, + number=1, + enum="Guardrail.ModelSafety.HarmCategory", + ) + threshold: "Guardrail.ModelSafety.HarmBlockThreshold" = proto.Field( + proto.ENUM, + number=2, + enum="Guardrail.ModelSafety.HarmBlockThreshold", + ) + + safety_settings: MutableSequence["Guardrail.ModelSafety.SafetySetting"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Guardrail.ModelSafety.SafetySetting", + ) + ) + + class CodeCallback(proto.Message): + r"""Guardrail that blocks the conversation based on the code + callbacks provided. + + Attributes: + before_agent_callback (google.cloud.ces_v1beta.types.Callback): + Optional. The callback to execute before the + agent is called. Each callback function is + expected to return a structure (e.g., a dict or + object) containing at least: + + - 'decision': Either 'OK' or 'TRIGGER'. + - 'reason': A string explaining the decision. + A 'TRIGGER' decision may halt further + processing. + after_agent_callback (google.cloud.ces_v1beta.types.Callback): + Optional. The callback to execute after the + agent is called. Each callback function is + expected to return a structure (e.g., a dict or + object) containing at least: + + - 'decision': Either 'OK' or 'TRIGGER'. + - 'reason': A string explaining the decision. + A 'TRIGGER' decision may halt further + processing. + before_model_callback (google.cloud.ces_v1beta.types.Callback): + Optional. The callback to execute before the + model is called. If there are multiple calls to + the model, the callback will be executed + multiple times. Each callback function is + expected to return a structure (e.g., a dict or + object) containing at least: + + - 'decision': Either 'OK' or 'TRIGGER'. + - 'reason': A string explaining the decision. + A 'TRIGGER' decision may halt further + processing. + after_model_callback (google.cloud.ces_v1beta.types.Callback): + Optional. The callback to execute after the + model is called. If there are multiple calls to + the model, the callback will be executed + multiple times. Each callback function is + expected to return a structure (e.g., a dict or + object) containing at least: + + - 'decision': Either 'OK' or 'TRIGGER'. + - 'reason': A string explaining the decision. + A 'TRIGGER' decision may halt further + processing. + """ + + before_agent_callback: common.Callback = proto.Field( + proto.MESSAGE, + number=1, + message=common.Callback, + ) + after_agent_callback: common.Callback = proto.Field( + proto.MESSAGE, + number=2, + message=common.Callback, + ) + before_model_callback: common.Callback = proto.Field( + proto.MESSAGE, + number=3, + message=common.Callback, + ) + after_model_callback: common.Callback = proto.Field( + proto.MESSAGE, + number=4, + message=common.Callback, + ) + + content_filter: ContentFilter = proto.Field( + proto.MESSAGE, + number=8, + oneof="guardrail_type", + message=ContentFilter, + ) + llm_prompt_security: LlmPromptSecurity = proto.Field( + proto.MESSAGE, + number=9, + oneof="guardrail_type", + message=LlmPromptSecurity, + ) + llm_policy: LlmPolicy = proto.Field( + proto.MESSAGE, + number=10, + oneof="guardrail_type", + message=LlmPolicy, + ) + model_safety: ModelSafety = proto.Field( + proto.MESSAGE, + number=13, + oneof="guardrail_type", + message=ModelSafety, + ) + code_callback: CodeCallback = proto.Field( + proto.MESSAGE, + number=14, + oneof="guardrail_type", + message=CodeCallback, + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + enabled: bool = proto.Field( + proto.BOOL, + number=4, + ) + action: common.TriggerAction = proto.Field( + proto.MESSAGE, + number=5, + message=common.TriggerAction, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + etag: str = proto.Field( + proto.STRING, + number=11, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/mcp_tool.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/mcp_tool.py new file mode 100644 index 000000000000..27f91824fcf4 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/mcp_tool.py @@ -0,0 +1,113 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.ces_v1beta.types import auth, common, schema + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "McpTool", + }, +) + + +class McpTool(proto.Message): + r"""An MCP tool. + See + https://modelcontextprotocol.io/specification/2025-06-18/server/tools + for more details. + + Attributes: + name (str): + Required. The name of the MCP tool. + description (str): + Optional. The description of the MCP tool. + input_schema (google.cloud.ces_v1beta.types.Schema): + Optional. The schema of the input arguments + of the MCP tool. + output_schema (google.cloud.ces_v1beta.types.Schema): + Optional. The schema of the output arguments + of the MCP tool. + server_address (str): + Required. The server address of the MCP server, e.g., + "https://example.com/mcp/". If the server is built with the + MCP SDK, the url should be suffixed with "/mcp/". Only + Streamable HTTP transport based servers are supported. This + is the same as the server_address in the McpToolset. See + https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#streamable-http + for more details. + api_authentication (google.cloud.ces_v1beta.types.ApiAuthentication): + Optional. Authentication information required + to execute the tool against the MCP server. For + bearer token authentication, the token applies + only to tool execution, not to listing tools. + This requires that tools can be listed without + authentication. + tls_config (google.cloud.ces_v1beta.types.TlsConfig): + Optional. The TLS configuration. Includes the + custom server certificates that the client + should trust. + service_directory_config (google.cloud.ces_v1beta.types.ServiceDirectoryConfig): + Optional. Service Directory configuration for + VPC-SC, used to resolve service names within a + perimeter. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + input_schema: schema.Schema = proto.Field( + proto.MESSAGE, + number=3, + message=schema.Schema, + ) + output_schema: schema.Schema = proto.Field( + proto.MESSAGE, + number=4, + message=schema.Schema, + ) + server_address: str = proto.Field( + proto.STRING, + number=5, + ) + api_authentication: auth.ApiAuthentication = proto.Field( + proto.MESSAGE, + number=6, + message=auth.ApiAuthentication, + ) + tls_config: common.TlsConfig = proto.Field( + proto.MESSAGE, + number=7, + message=common.TlsConfig, + ) + service_directory_config: common.ServiceDirectoryConfig = proto.Field( + proto.MESSAGE, + number=8, + message=common.ServiceDirectoryConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/mcp_toolset.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/mcp_toolset.py new file mode 100644 index 000000000000..11f3ccc47c12 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/mcp_toolset.py @@ -0,0 +1,84 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.ces_v1beta.types import auth, common + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "McpToolset", + }, +) + + +class McpToolset(proto.Message): + r"""A toolset that contains a list of tools that are offered by + the MCP server. + + Attributes: + server_address (str): + Required. The address of the MCP server, for + example, "https://example.com/mcp/". If the + server is built with the MCP SDK, the url should + be suffixed with + "/mcp/". Only Streamable HTTP transport based + servers are supported. See + https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#streamable-http + for more details. + api_authentication (google.cloud.ces_v1beta.types.ApiAuthentication): + Optional. Authentication information required + to access tools and execute a tool against the + MCP server. For bearer token authentication, the + token applies only to tool execution, not to + listing tools. This requires that tools can be + listed without authentication. + service_directory_config (google.cloud.ces_v1beta.types.ServiceDirectoryConfig): + Optional. Service Directory configuration for + VPC-SC, used to resolve service names within a + perimeter. + tls_config (google.cloud.ces_v1beta.types.TlsConfig): + Optional. The TLS configuration. Includes the + custom server certificates that the client + should trust. + """ + + server_address: str = proto.Field( + proto.STRING, + number=1, + ) + api_authentication: auth.ApiAuthentication = proto.Field( + proto.MESSAGE, + number=2, + message=auth.ApiAuthentication, + ) + service_directory_config: common.ServiceDirectoryConfig = proto.Field( + proto.MESSAGE, + number=3, + message=common.ServiceDirectoryConfig, + ) + tls_config: common.TlsConfig = proto.Field( + proto.MESSAGE, + number=4, + message=common.TlsConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/omnichannel.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/omnichannel.py new file mode 100644 index 000000000000..7f765aef98de --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/omnichannel.py @@ -0,0 +1,246 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "Omnichannel", + "OmnichannelIntegrationConfig", + }, +) + + +class Omnichannel(proto.Message): + r"""Represents an Omnichannel resource. + + Attributes: + name (str): + Identifier. The unique identifier of the omnichannel + resource. Format: + ``projects/{project}/locations/{location}/omnichannels/{omnichannel}`` + display_name (str): + Required. Display name of the omnichannel + resource. + description (str): + Optional. Human-readable description of the + omnichannel resource. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the omnichannel + resource was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the omnichannel + resource was last updated. + etag (str): + Output only. Etag used to ensure the object + hasn't changed during a read-modify-write + operation. + integration_config (google.cloud.ces_v1beta.types.OmnichannelIntegrationConfig): + Optional. The integration config for the + omnichannel resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + etag: str = proto.Field( + proto.STRING, + number=6, + ) + integration_config: "OmnichannelIntegrationConfig" = proto.Field( + proto.MESSAGE, + number=7, + message="OmnichannelIntegrationConfig", + ) + + +class OmnichannelIntegrationConfig(proto.Message): + r"""OmnichannelIntegrationConfig contains all App integration + configs. + + Attributes: + channel_configs (MutableMapping[str, google.cloud.ces_v1beta.types.OmnichannelIntegrationConfig.ChannelConfig]): + Optional. Various of configuration for + handling App events. + subscriber_configs (MutableMapping[str, google.cloud.ces_v1beta.types.OmnichannelIntegrationConfig.SubscriberConfig]): + Optional. Various of subscribers configs. + routing_configs (MutableMapping[str, google.cloud.ces_v1beta.types.OmnichannelIntegrationConfig.RoutingConfig]): + Optional. The key of routing_configs is a key of + ``app_configs``, value is a ``RoutingConfig``, which + contains subscriber's key. + """ + + class ChannelConfig(proto.Message): + r"""ChannelConfig contains config for various of app integration. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + whatsapp_config (google.cloud.ces_v1beta.types.OmnichannelIntegrationConfig.WhatsappConfig): + WhatsApp config. + + This field is a member of `oneof`_ ``channel_config``. + """ + + whatsapp_config: "OmnichannelIntegrationConfig.WhatsappConfig" = proto.Field( + proto.MESSAGE, + number=1, + oneof="channel_config", + message="OmnichannelIntegrationConfig.WhatsappConfig", + ) + + class WhatsappConfig(proto.Message): + r"""How Omnichannel should receive/reply events from WhatsApp. + + Attributes: + phone_number_id (str): + The Phone Number ID associated with the + WhatsApp Business Account. + phone_number (str): + The phone number used for sending/receiving + messages. + whatsapp_business_account_id (str): + The customer's WhatsApp Business Account + (WABA) ID. + webhook_verify_token (str): + The verify token configured in the Meta App + Dashboard for webhook verification. + whatsapp_business_token (str): + The access token for authenticating API calls + to the WhatsApp Cloud API. + https://developers.facebook.com/docs/whatsapp/business-management-api/get-started/#business-integration-system-user-access-tokens + meta_business_portfolio_id (str): + The Meta Business Portfolio (MBP) ID. + https://www.facebook.com/business/help/1710077379203657 + """ + + phone_number_id: str = proto.Field( + proto.STRING, + number=1, + ) + phone_number: str = proto.Field( + proto.STRING, + number=2, + ) + whatsapp_business_account_id: str = proto.Field( + proto.STRING, + number=3, + ) + webhook_verify_token: str = proto.Field( + proto.STRING, + number=4, + ) + whatsapp_business_token: str = proto.Field( + proto.STRING, + number=5, + ) + meta_business_portfolio_id: str = proto.Field( + proto.STRING, + number=6, + ) + + class SubscriberConfig(proto.Message): + r"""Configs of subscribers. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + ces_app_config (google.cloud.ces_v1beta.types.OmnichannelIntegrationConfig.CesAppConfig): + Ces app config. + + This field is a member of `oneof`_ ``subscriber_config``. + """ + + ces_app_config: "OmnichannelIntegrationConfig.CesAppConfig" = proto.Field( + proto.MESSAGE, + number=1, + oneof="subscriber_config", + message="OmnichannelIntegrationConfig.CesAppConfig", + ) + + class CesAppConfig(proto.Message): + r"""Configs for CES app. + + Attributes: + app (str): + The unique identifier of the CES app. Format: + ``projects/{project}/locations/{location}/apps/{app}`` + """ + + app: str = proto.Field( + proto.STRING, + number=1, + ) + + class RoutingConfig(proto.Message): + r"""Routing config specify how/who to route app events to a + subscriber. + + Attributes: + subscriber_key (str): + The key of the subscriber. + """ + + subscriber_key: str = proto.Field( + proto.STRING, + number=1, + ) + + channel_configs: MutableMapping[str, ChannelConfig] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=1, + message=ChannelConfig, + ) + subscriber_configs: MutableMapping[str, SubscriberConfig] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message=SubscriberConfig, + ) + routing_configs: MutableMapping[str, RoutingConfig] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=3, + message=RoutingConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/omnichannel_service.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/omnichannel_service.py new file mode 100644 index 000000000000..af67139c0f59 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/omnichannel_service.py @@ -0,0 +1,69 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "OmnichannelOperationMetadata", + }, +) + + +class OmnichannelOperationMetadata(proto.Message): + r"""Represents the metadata of the long-running operation. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation was + created. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the operation finished + running. + status_message (str): + Output only. Human-readable status of the + operation, if any. + requested_cancellation (bool): + Output only. Identifies whether the user has + requested cancellation of the operation. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + status_message: str = proto.Field( + proto.STRING, + number=3, + ) + requested_cancellation: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/open_api_tool.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/open_api_tool.py new file mode 100644 index 000000000000..40294be0447f --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/open_api_tool.py @@ -0,0 +1,106 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.ces_v1beta.types import auth, common + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "OpenApiTool", + }, +) + + +class OpenApiTool(proto.Message): + r"""A remote API tool defined by an OpenAPI schema. + + Attributes: + open_api_schema (str): + Required. The OpenAPI schema in JSON or YAML + format. + name (str): + Optional. The name of the tool. If not provided, the name of + the tool will be derived from the OpenAPI schema, from + ``operation.operationId``. + description (str): + Optional. The description of the tool. If not provided, the + description of the tool will be derived from the OpenAPI + schema, from ``operation.description`` or + ``operation.summary``. + api_authentication (google.cloud.ces_v1beta.types.ApiAuthentication): + Optional. Authentication information required + by the API. + tls_config (google.cloud.ces_v1beta.types.TlsConfig): + Optional. The TLS configuration. Includes the + custom server certificates that the client will + trust. + service_directory_config (google.cloud.ces_v1beta.types.ServiceDirectoryConfig): + Optional. Service Directory configuration. + ignore_unknown_fields_ (bool): + Optional. If true, the agent will ignore + unknown fields in the API response. + url (str): + Optional. The server URL of the Open API schema. This field + is only set in tools in the environment dependencies during + the export process if the schema contains a server url. + During the import process, if this url is present in the + environment dependencies and the schema has the $env_var + placeholder, it will replace the placeholder in the schema. + """ + + open_api_schema: str = proto.Field( + proto.STRING, + number=1, + ) + name: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + api_authentication: auth.ApiAuthentication = proto.Field( + proto.MESSAGE, + number=4, + message=auth.ApiAuthentication, + ) + tls_config: common.TlsConfig = proto.Field( + proto.MESSAGE, + number=5, + message=common.TlsConfig, + ) + service_directory_config: common.ServiceDirectoryConfig = proto.Field( + proto.MESSAGE, + number=6, + message=common.ServiceDirectoryConfig, + ) + ignore_unknown_fields_: bool = proto.Field( + proto.BOOL, + number=7, + ) + url: str = proto.Field( + proto.STRING, + number=8, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/open_api_toolset.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/open_api_toolset.py new file mode 100644 index 000000000000..839a63133b40 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/open_api_toolset.py @@ -0,0 +1,89 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.ces_v1beta.types import auth, common + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "OpenApiToolset", + }, +) + + +class OpenApiToolset(proto.Message): + r"""A toolset that contains a list of tools that are defined by + an OpenAPI schema. + + Attributes: + open_api_schema (str): + Required. The OpenAPI schema of the toolset. + api_authentication (google.cloud.ces_v1beta.types.ApiAuthentication): + Optional. Authentication information required + by the API. + tls_config (google.cloud.ces_v1beta.types.TlsConfig): + Optional. The TLS configuration. Includes the + custom server certificates + service_directory_config (google.cloud.ces_v1beta.types.ServiceDirectoryConfig): + Optional. Service Directory configuration. + ignore_unknown_fields_ (bool): + Optional. If true, the agent will ignore + unknown fields in the API response for all + operations defined in the OpenAPI schema. + url (str): + Optional. The server URL of the Open API schema. This field + is only set in toolsets in the environment dependencies + during the export process if the schema contains a server + url. During the import process, if this url is present in + the environment dependencies and the schema has the $env_var + placeholder, it will replace the placeholder in the schema. + """ + + open_api_schema: str = proto.Field( + proto.STRING, + number=1, + ) + api_authentication: auth.ApiAuthentication = proto.Field( + proto.MESSAGE, + number=2, + message=auth.ApiAuthentication, + ) + tls_config: common.TlsConfig = proto.Field( + proto.MESSAGE, + number=3, + message=common.TlsConfig, + ) + service_directory_config: common.ServiceDirectoryConfig = proto.Field( + proto.MESSAGE, + number=4, + message=common.ServiceDirectoryConfig, + ) + ignore_unknown_fields_: bool = proto.Field( + proto.BOOL, + number=5, + ) + url: str = proto.Field( + proto.STRING, + number=6, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/python_function.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/python_function.py new file mode 100644 index 000000000000..79d882ac314c --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/python_function.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "PythonFunction", + }, +) + + +class PythonFunction(proto.Message): + r"""A Python function tool. + + Attributes: + name (str): + Optional. The name of the Python function to + execute. Must match a Python function name + defined in the python code. Case sensitive. If + the name is not provided, the first function + defined in the python code will be used. + python_code (str): + Optional. The Python code to execute for the + tool. + description (str): + Output only. The description of the Python + function, parsed from the python code's + docstring. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + python_code: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/schema.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/schema.py new file mode 100644 index 000000000000..f26b79d246c9 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/schema.py @@ -0,0 +1,239 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import google.protobuf.struct_pb2 as struct_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "Schema", + }, +) + + +class Schema(proto.Message): + r"""Represents a select subset of an OpenAPI 3.0 schema object. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + type_ (google.cloud.ces_v1beta.types.Schema.Type): + Required. The type of the data. + properties (MutableMapping[str, google.cloud.ces_v1beta.types.Schema]): + Optional. Properties of Type.OBJECT. + required (MutableSequence[str]): + Optional. Required properties of Type.OBJECT. + description (str): + Optional. The description of the data. + items (google.cloud.ces_v1beta.types.Schema): + Optional. Schema of the elements of + Type.ARRAY. + nullable (bool): + Optional. Indicates if the value may be null. + unique_items (bool): + Optional. Indicate the items in the array + must be unique. Only applies to TYPE.ARRAY. + prefix_items (MutableSequence[google.cloud.ces_v1beta.types.Schema]): + Optional. Schemas of initial elements of + Type.ARRAY. + additional_properties (google.cloud.ces_v1beta.types.Schema): + Optional. Can either be a boolean or an + object, controls the presence of additional + properties. + any_of (MutableSequence[google.cloud.ces_v1beta.types.Schema]): + Optional. The value should be validated + against any (one or more) of the subschemas in + the list. + enum (MutableSequence[str]): + Optional. Possible values of the element of primitive type + with enum format. Examples: + + 1. We can define direction as : {type:STRING, format:enum, + enum:["EAST", NORTH", "SOUTH", "WEST"]} + 2. We can define apartment number as : {type:INTEGER, + format:enum, enum:["101", "201", "301"]} + default (google.protobuf.struct_pb2.Value): + Optional. Default value of the data. + ref (str): + Optional. Allows indirect references between schema nodes. + The value should be a valid reference to a child of the root + ``defs``. + + For example, the following schema defines a reference to a + schema node named "Pet": + + :: + + type: object + properties: + pet: + ref: #/defs/Pet + defs: + Pet: + type: object + properties: + name: + type: string + + The value of the "pet" property is a reference to the schema + node named "Pet". See details in + https://json-schema.org/understanding-json-schema/structuring. + defs (MutableMapping[str, google.cloud.ces_v1beta.types.Schema]): + Optional. A map of definitions for use by ``ref``. Only + allowed at the root of the schema. + title (str): + Optional. The title of the schema. + min_items (int): + Optional. Minimum number of the elements for + Type.ARRAY. + max_items (int): + Optional. Maximum number of the elements for + Type.ARRAY. + minimum (float): + Optional. Minimum value for Type.INTEGER and + Type.NUMBER. + + This field is a member of `oneof`_ ``_minimum``. + maximum (float): + Optional. Maximum value for Type.INTEGER and + Type.NUMBER. + + This field is a member of `oneof`_ ``_maximum``. + """ + + class Type(proto.Enum): + r"""OpenAPI data types. + + Values: + TYPE_UNSPECIFIED (0): + Type unspecified. + STRING (1): + String type. + INTEGER (2): + Integer type. + NUMBER (3): + Number type. + BOOLEAN (4): + Boolean type. + OBJECT (5): + Object type. + ARRAY (6): + Array type. + """ + + TYPE_UNSPECIFIED = 0 + STRING = 1 + INTEGER = 2 + NUMBER = 3 + BOOLEAN = 4 + OBJECT = 5 + ARRAY = 6 + + type_: Type = proto.Field( + proto.ENUM, + number=1, + enum=Type, + ) + properties: MutableMapping[str, "Schema"] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message="Schema", + ) + required: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + description: str = proto.Field( + proto.STRING, + number=4, + ) + items: "Schema" = proto.Field( + proto.MESSAGE, + number=5, + message="Schema", + ) + nullable: bool = proto.Field( + proto.BOOL, + number=6, + ) + unique_items: bool = proto.Field( + proto.BOOL, + number=7, + ) + prefix_items: MutableSequence["Schema"] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message="Schema", + ) + additional_properties: "Schema" = proto.Field( + proto.MESSAGE, + number=9, + message="Schema", + ) + any_of: MutableSequence["Schema"] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message="Schema", + ) + enum: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=11, + ) + default: struct_pb2.Value = proto.Field( + proto.MESSAGE, + number=12, + message=struct_pb2.Value, + ) + ref: str = proto.Field( + proto.STRING, + number=13, + ) + defs: MutableMapping[str, "Schema"] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=14, + message="Schema", + ) + title: str = proto.Field( + proto.STRING, + number=15, + ) + min_items: int = proto.Field( + proto.INT64, + number=16, + ) + max_items: int = proto.Field( + proto.INT64, + number=17, + ) + minimum: float = proto.Field( + proto.DOUBLE, + number=18, + optional=True, + ) + maximum: float = proto.Field( + proto.DOUBLE, + number=19, + optional=True, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/search_suggestions.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/search_suggestions.py new file mode 100644 index 000000000000..e569b0ec10a9 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/search_suggestions.py @@ -0,0 +1,80 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "GoogleSearchSuggestions", + "WebSearchQuery", + }, +) + + +class GoogleSearchSuggestions(proto.Message): + r"""Search suggestions from [Google Search + Tool][google.cloud.ces.v1beta.GoogleSearchTool]. + + Attributes: + htmls (MutableSequence[str]): + Compliant HTML and CSS styling for search suggestions. The + provided HTML and CSS automatically adapts to your device + settings, displaying in either light or dark mode indicated + by ``@media(prefers-color-scheme)``. + web_search_queries (MutableSequence[google.cloud.ces_v1beta.types.WebSearchQuery]): + List of queries used to perform the google + search along with the search result URIs forming + the search suggestions. + """ + + htmls: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + web_search_queries: MutableSequence["WebSearchQuery"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="WebSearchQuery", + ) + + +class WebSearchQuery(proto.Message): + r"""Represents a single web search query and its associated + search uri. + + Attributes: + query (str): + The search query text. + uri (str): + The URI to the Google Search results page for + the query. + """ + + query: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/session_service.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/session_service.py new file mode 100644 index 000000000000..836a19463a43 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/session_service.py @@ -0,0 +1,801 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import google.protobuf.struct_pb2 as struct_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.ces_v1beta.types import common, example, search_suggestions + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "AudioEncoding", + "InputAudioConfig", + "OutputAudioConfig", + "SessionConfig", + "ToolCalls", + "ToolResponses", + "Citations", + "Event", + "SessionInput", + "SessionOutput", + "RecognitionResult", + "InterruptionSignal", + "EndSession", + "GoAway", + "RunSessionRequest", + "RunSessionResponse", + "BidiSessionClientMessage", + "BidiSessionServerMessage", + }, +) + + +class AudioEncoding(proto.Enum): + r"""AudioEncoding specifies the encoding format for audio data. + + Values: + AUDIO_ENCODING_UNSPECIFIED (0): + Unspecified audio encoding. + LINEAR16 (1): + 16-bit linear PCM audio encoding. + MULAW (2): + 8-bit samples that compand 14-bit audio + samples using G.711 PCMU/mu-law. + ALAW (3): + 8-bit samples that compand 14-bit audio + samples using G.711 PCMU/A-law. + """ + + AUDIO_ENCODING_UNSPECIFIED = 0 + LINEAR16 = 1 + MULAW = 2 + ALAW = 3 + + +class InputAudioConfig(proto.Message): + r"""InputAudioConfig configures how the CES agent should + interpret the incoming audio data. + + Attributes: + audio_encoding (google.cloud.ces_v1beta.types.AudioEncoding): + Required. The encoding of the input audio + data. + sample_rate_hertz (int): + Required. The sample rate (in Hertz) of the + input audio data. + noise_suppression_level (str): + Optional. Whether to enable noise suppression on the input + audio. Available values are "low", "moderate", "high", + "very_high". + """ + + audio_encoding: "AudioEncoding" = proto.Field( + proto.ENUM, + number=1, + enum="AudioEncoding", + ) + sample_rate_hertz: int = proto.Field( + proto.INT32, + number=2, + ) + noise_suppression_level: str = proto.Field( + proto.STRING, + number=6, + ) + + +class OutputAudioConfig(proto.Message): + r"""OutputAudioConfig configures how the CES agent should + synthesize outgoing audio responses. + + Attributes: + audio_encoding (google.cloud.ces_v1beta.types.AudioEncoding): + Required. The encoding of the output audio + data. + sample_rate_hertz (int): + Required. The sample rate (in Hertz) of the + output audio data. + """ + + audio_encoding: "AudioEncoding" = proto.Field( + proto.ENUM, + number=1, + enum="AudioEncoding", + ) + sample_rate_hertz: int = proto.Field( + proto.INT32, + number=2, + ) + + +class SessionConfig(proto.Message): + r"""The configuration for the session. + + Attributes: + session (str): + Required. The unique identifier of the session. Format: + ``projects/{project}/locations/{location}/apps/{app}/sessions/{session}`` + input_audio_config (google.cloud.ces_v1beta.types.InputAudioConfig): + Optional. Configuration for processing the + input audio. + output_audio_config (google.cloud.ces_v1beta.types.OutputAudioConfig): + Optional. Configuration for generating the + output audio. + historical_contexts (MutableSequence[google.cloud.ces_v1beta.types.Message]): + Optional. The historical context of the + session, including user inputs, agent responses, + and other messages. Typically, CES agent would + manage session automatically so client doesn't + need to explicitly populate this field. However, + client can optionally override the historical + contexts to force the session start from certain + state. + entry_agent (str): + Optional. The entry agent to handle the session. If not + specified, the session will be handled by the [root + agent][google.cloud.ces.v1beta.App.root_agent] of the app. + Format: + ``projects/{project}/locations/{location}/agents/{agent}`` + deployment (str): + Optional. The deployment of the app to use for the session. + Format: + ``projects/{project}/locations/{location}/apps/{app}/deployments/{deployment}`` + time_zone (str): + Optional. The time zone of the user. If provided, the agent + will use the time zone for date and time related variables. + Otherwise, the agent will use the time zone specified in the + App.time_zone_settings. + + The format is the IANA Time Zone Database time zone, e.g. + "America/Los_Angeles". + remote_dialogflow_query_parameters (google.cloud.ces_v1beta.types.SessionConfig.RemoteDialogflowQueryParameters): + Optional. + `QueryParameters `__ + to send to the remote + `Dialogflow `__ + agent when the session control is transferred to the remote + agent. + """ + + class RemoteDialogflowQueryParameters(proto.Message): + r"""`QueryParameters `__ + to send to the remote + `Dialogflow `__ + agent when the session control is transferred to the remote agent. + + Attributes: + webhook_headers (MutableMapping[str, str]): + Optional. The HTTP headers to be sent as webhook_headers in + `QueryParameters `__. + payload (google.protobuf.struct_pb2.Struct): + Optional. The payload to be sent in + `QueryParameters `__. + end_user_metadata (google.protobuf.struct_pb2.Struct): + Optional. The end user metadata to be sent in + `QueryParameters `__. + """ + + webhook_headers: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=1, + ) + payload: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=2, + message=struct_pb2.Struct, + ) + end_user_metadata: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=3, + message=struct_pb2.Struct, + ) + + session: str = proto.Field( + proto.STRING, + number=1, + ) + input_audio_config: "InputAudioConfig" = proto.Field( + proto.MESSAGE, + number=2, + message="InputAudioConfig", + ) + output_audio_config: "OutputAudioConfig" = proto.Field( + proto.MESSAGE, + number=3, + message="OutputAudioConfig", + ) + historical_contexts: MutableSequence[example.Message] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message=example.Message, + ) + entry_agent: str = proto.Field( + proto.STRING, + number=12, + ) + deployment: str = proto.Field( + proto.STRING, + number=8, + ) + time_zone: str = proto.Field( + proto.STRING, + number=11, + ) + remote_dialogflow_query_parameters: RemoteDialogflowQueryParameters = proto.Field( + proto.MESSAGE, + number=15, + message=RemoteDialogflowQueryParameters, + ) + + +class ToolCalls(proto.Message): + r"""Request for the client to execute the tools and return the + execution results before continuing the session. + + Attributes: + tool_calls (MutableSequence[google.cloud.ces_v1beta.types.ToolCall]): + Optional. The list of tool calls to execute. + """ + + tool_calls: MutableSequence[example.ToolCall] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=example.ToolCall, + ) + + +class ToolResponses(proto.Message): + r"""Execution results for the requested tool calls from the + client. + + Attributes: + tool_responses (MutableSequence[google.cloud.ces_v1beta.types.ToolResponse]): + Optional. The list of tool execution results. + """ + + tool_responses: MutableSequence[example.ToolResponse] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=example.ToolResponse, + ) + + +class Citations(proto.Message): + r"""Citations associated with the agent response. + + Attributes: + cited_chunks (MutableSequence[google.cloud.ces_v1beta.types.Citations.CitedChunk]): + List of cited pieces of information. + """ + + class CitedChunk(proto.Message): + r"""Piece of cited information. + + Attributes: + uri (str): + URI used for citation. + title (str): + Title of the cited document. + text (str): + Text used for citation. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + title: str = proto.Field( + proto.STRING, + number=2, + ) + text: str = proto.Field( + proto.STRING, + number=3, + ) + + cited_chunks: MutableSequence[CitedChunk] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=CitedChunk, + ) + + +class Event(proto.Message): + r"""Event input. + + Attributes: + event (str): + Required. The name of the event. + """ + + event: str = proto.Field( + proto.STRING, + number=1, + ) + + +class SessionInput(proto.Message): + r"""Input for the session. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + text (str): + Optional. Text data from the end user. + + This field is a member of `oneof`_ ``input_type``. + dtmf (str): + Optional. DTMF digits from the end user. + + This field is a member of `oneof`_ ``input_type``. + audio (bytes): + Optional. Audio data from the end user. + + This field is a member of `oneof`_ ``input_type``. + tool_responses (google.cloud.ces_v1beta.types.ToolResponses): + Optional. Execution results for the tool + calls from the client. + + This field is a member of `oneof`_ ``input_type``. + image (google.cloud.ces_v1beta.types.Image): + Optional. Image data from the end user. + + This field is a member of `oneof`_ ``input_type``. + blob (google.cloud.ces_v1beta.types.Blob): + Optional. Blob data from the end user. + + This field is a member of `oneof`_ ``input_type``. + variables (google.protobuf.struct_pb2.Struct): + Optional. Contextual variables for the session, keyed by + name. Only variables declared in the app will be used by the + CES agent. + + Unrecognized variables will still be sent to the [Dialogflow + agent][Agent.RemoteDialogflowAgent] as additional session + parameters. + + This field is a member of `oneof`_ ``input_type``. + event (google.cloud.ces_v1beta.types.Event): + Optional. Event input. + + This field is a member of `oneof`_ ``input_type``. + will_continue (bool): + Optional. A flag to indicate if the current message is a + fragment of a larger input in the bidi streaming session. + + When set to ``true``, the agent defers processing until it + receives a subsequent message where ``will_continue`` is + ``false``, or until the system detects an endpoint in the + audio input. + + NOTE: This field does not apply to audio and DTMF inputs, as + they are always processed automatically based on the + endpointing signal. + """ + + text: str = proto.Field( + proto.STRING, + number=1, + oneof="input_type", + ) + dtmf: str = proto.Field( + proto.STRING, + number=6, + oneof="input_type", + ) + audio: bytes = proto.Field( + proto.BYTES, + number=2, + oneof="input_type", + ) + tool_responses: "ToolResponses" = proto.Field( + proto.MESSAGE, + number=3, + oneof="input_type", + message="ToolResponses", + ) + image: example.Image = proto.Field( + proto.MESSAGE, + number=4, + oneof="input_type", + message=example.Image, + ) + blob: example.Blob = proto.Field( + proto.MESSAGE, + number=7, + oneof="input_type", + message=example.Blob, + ) + variables: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=5, + oneof="input_type", + message=struct_pb2.Struct, + ) + event: "Event" = proto.Field( + proto.MESSAGE, + number=9, + oneof="input_type", + message="Event", + ) + will_continue: bool = proto.Field( + proto.BOOL, + number=8, + ) + + +class SessionOutput(proto.Message): + r"""Output for the session. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + text (str): + Output text from the CES agent. + + This field is a member of `oneof`_ ``output_type``. + audio (bytes): + Output audio from the CES agent. + + This field is a member of `oneof`_ ``output_type``. + tool_calls (google.cloud.ces_v1beta.types.ToolCalls): + Request for the client to execute the tools. + + This field is a member of `oneof`_ ``output_type``. + citations (google.cloud.ces_v1beta.types.Citations): + Citations that provide the source information + for the agent's generated text. + + This field is a member of `oneof`_ ``output_type``. + google_search_suggestions (google.cloud.ces_v1beta.types.GoogleSearchSuggestions): + The suggestions returned from Google Search as a result of + invoking the + [GoogleSearchTool][google.cloud.ces.v1beta.GoogleSearchTool]. + + This field is a member of `oneof`_ ``output_type``. + end_session (google.cloud.ces_v1beta.types.EndSession): + Indicates the session has ended. + + This field is a member of `oneof`_ ``output_type``. + payload (google.protobuf.struct_pb2.Struct): + Custom payload with structured output from + the CES agent. + + This field is a member of `oneof`_ ``output_type``. + turn_index (int): + Indicates the sequential order of + conversation turn to which this output belongs + to, starting from 1. + turn_completed (bool): + If true, the CES agent has detected the end + of the current conversation turn and will + provide no further output for this turn. + diagnostic_info (google.cloud.ces_v1beta.types.SessionOutput.DiagnosticInfo): + Optional. Diagnostic information contains execution details + during the processing of the input. Only populated in the + last SessionOutput (with ``turn_completed=true``) for each + turn. + """ + + class DiagnosticInfo(proto.Message): + r"""Contains execution details during the processing. + + Attributes: + messages (MutableSequence[google.cloud.ces_v1beta.types.Message]): + List of the messages that happened during the + processing. + root_span (google.cloud.ces_v1beta.types.Span): + A trace of the entire request processing, + represented as a root span. This span can + contain nested child spans for specific + operations. + """ + + messages: MutableSequence[example.Message] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=example.Message, + ) + root_span: common.Span = proto.Field( + proto.MESSAGE, + number=3, + message=common.Span, + ) + + text: str = proto.Field( + proto.STRING, + number=1, + oneof="output_type", + ) + audio: bytes = proto.Field( + proto.BYTES, + number=2, + oneof="output_type", + ) + tool_calls: "ToolCalls" = proto.Field( + proto.MESSAGE, + number=3, + oneof="output_type", + message="ToolCalls", + ) + citations: "Citations" = proto.Field( + proto.MESSAGE, + number=8, + oneof="output_type", + message="Citations", + ) + google_search_suggestions: search_suggestions.GoogleSearchSuggestions = proto.Field( + proto.MESSAGE, + number=10, + oneof="output_type", + message=search_suggestions.GoogleSearchSuggestions, + ) + end_session: "EndSession" = proto.Field( + proto.MESSAGE, + number=9, + oneof="output_type", + message="EndSession", + ) + payload: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=11, + oneof="output_type", + message=struct_pb2.Struct, + ) + turn_index: int = proto.Field( + proto.INT32, + number=6, + ) + turn_completed: bool = proto.Field( + proto.BOOL, + number=4, + ) + diagnostic_info: DiagnosticInfo = proto.Field( + proto.MESSAGE, + number=7, + message=DiagnosticInfo, + ) + + +class RecognitionResult(proto.Message): + r"""Speech recognition result for the audio input. + + Attributes: + transcript (str): + Optional. Concatenated user speech segments + captured during the current turn. + """ + + transcript: str = proto.Field( + proto.STRING, + number=1, + ) + + +class InterruptionSignal(proto.Message): + r"""Indicates the agent's audio response has been interrupted. + The client should immediately stop any current audio playback + (e.g., due to user barge-in or a new agent response being + generated). + + Attributes: + barge_in (bool): + Whether the interruption is caused by a user + barge-in event. + """ + + barge_in: bool = proto.Field( + proto.BOOL, + number=1, + ) + + +class EndSession(proto.Message): + r"""Indicates the session has terminated, due to either + successful completion (e.g. user says "Good bye!" ) or an agent + escalation. + + The agent will not process any further inputs after session is + terminated and the client should half-close and disconnect after + receiving all remaining responses from the agent. + + Attributes: + metadata (google.protobuf.struct_pb2.Struct): + Optional. Provides additional information + about the end session signal, such as the reason + for ending the session. + """ + + metadata: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=1, + message=struct_pb2.Struct, + ) + + +class GoAway(proto.Message): + r"""Indicates that the server will disconnect soon and the client + should half-close and restart the connection. + + """ + + +class RunSessionRequest(proto.Message): + r"""Request message for + [SessionService.RunSession][google.cloud.ces.v1beta.SessionService.RunSession]. + + Attributes: + config (google.cloud.ces_v1beta.types.SessionConfig): + Required. The configuration for the session. + inputs (MutableSequence[google.cloud.ces_v1beta.types.SessionInput]): + Required. Inputs for the session. + """ + + config: "SessionConfig" = proto.Field( + proto.MESSAGE, + number=1, + message="SessionConfig", + ) + inputs: MutableSequence["SessionInput"] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="SessionInput", + ) + + +class RunSessionResponse(proto.Message): + r"""Response message for + [SessionService.RunSession][google.cloud.ces.v1beta.SessionService.RunSession]. + + Attributes: + outputs (MutableSequence[google.cloud.ces_v1beta.types.SessionOutput]): + Outputs for the session. + """ + + outputs: MutableSequence["SessionOutput"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="SessionOutput", + ) + + +class BidiSessionClientMessage(proto.Message): + r"""The top-level message sent by the client for the + [SessionService.BidiRunSession][google.cloud.ces.v1beta.SessionService.BidiRunSession] + method. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + config (google.cloud.ces_v1beta.types.SessionConfig): + Optional. The initial config message for the + session. + + This field is a member of `oneof`_ ``message_type``. + realtime_input (google.cloud.ces_v1beta.types.SessionInput): + Optional. Realtime input for the session. + + This field is a member of `oneof`_ ``message_type``. + """ + + config: "SessionConfig" = proto.Field( + proto.MESSAGE, + number=1, + oneof="message_type", + message="SessionConfig", + ) + realtime_input: "SessionInput" = proto.Field( + proto.MESSAGE, + number=2, + oneof="message_type", + message="SessionInput", + ) + + +class BidiSessionServerMessage(proto.Message): + r"""The top-level message returned from + [SessionService.BidiRunSession][google.cloud.ces.v1beta.SessionService.BidiRunSession] + method. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + session_output (google.cloud.ces_v1beta.types.SessionOutput): + Optional. Processing result from the CES + agent. + + This field is a member of `oneof`_ ``message_type``. + recognition_result (google.cloud.ces_v1beta.types.RecognitionResult): + Optional. Realtime speech recognition result + for the audio input. + + This field is a member of `oneof`_ ``message_type``. + interruption_signal (google.cloud.ces_v1beta.types.InterruptionSignal): + Optional. Indicates the agent's audio + response has been interrupted. + + This field is a member of `oneof`_ ``message_type``. + end_session (google.cloud.ces_v1beta.types.EndSession): + Optional. Indicates that the session has + ended. + + This field is a member of `oneof`_ ``message_type``. + go_away (google.cloud.ces_v1beta.types.GoAway): + Optional. Indicates that the server will + disconnect soon and the client should half-close + and restart the connection. + + This field is a member of `oneof`_ ``message_type``. + """ + + session_output: "SessionOutput" = proto.Field( + proto.MESSAGE, + number=1, + oneof="message_type", + message="SessionOutput", + ) + recognition_result: "RecognitionResult" = proto.Field( + proto.MESSAGE, + number=2, + oneof="message_type", + message="RecognitionResult", + ) + interruption_signal: "InterruptionSignal" = proto.Field( + proto.MESSAGE, + number=3, + oneof="message_type", + message="InterruptionSignal", + ) + end_session: "EndSession" = proto.Field( + proto.MESSAGE, + number=5, + oneof="message_type", + message="EndSession", + ) + go_away: "GoAway" = proto.Field( + proto.MESSAGE, + number=6, + oneof="message_type", + message="GoAway", + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/system_tool.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/system_tool.py new file mode 100644 index 000000000000..d3eb0c85d70a --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/system_tool.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "SystemTool", + }, +) + + +class SystemTool(proto.Message): + r"""Pre-defined system tool. + + Attributes: + name (str): + Required. The name of the system tool. + description (str): + Output only. The description of the system + tool. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/tool.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/tool.py new file mode 100644 index 000000000000..32640c21c66a --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/tool.py @@ -0,0 +1,235 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.ces_v1beta.types import client_function as gcc_client_function +from google.cloud.ces_v1beta.types import common, fakes +from google.cloud.ces_v1beta.types import connector_tool as gcc_connector_tool +from google.cloud.ces_v1beta.types import data_store_tool as gcc_data_store_tool +from google.cloud.ces_v1beta.types import file_search_tool as gcc_file_search_tool +from google.cloud.ces_v1beta.types import google_search_tool as gcc_google_search_tool +from google.cloud.ces_v1beta.types import mcp_tool as gcc_mcp_tool +from google.cloud.ces_v1beta.types import open_api_tool as gcc_open_api_tool +from google.cloud.ces_v1beta.types import python_function as gcc_python_function +from google.cloud.ces_v1beta.types import system_tool as gcc_system_tool +from google.cloud.ces_v1beta.types import widget_tool as gcc_widget_tool + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "Tool", + }, +) + + +class Tool(proto.Message): + r"""A tool represents an action that the CES agent can take to + achieve certain goals. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + client_function (google.cloud.ces_v1beta.types.ClientFunction): + Optional. The client function. + + This field is a member of `oneof`_ ``tool_type``. + open_api_tool (google.cloud.ces_v1beta.types.OpenApiTool): + Optional. The open API tool. + + This field is a member of `oneof`_ ``tool_type``. + google_search_tool (google.cloud.ces_v1beta.types.GoogleSearchTool): + Optional. The google search tool. + + This field is a member of `oneof`_ ``tool_type``. + connector_tool (google.cloud.ces_v1beta.types.ConnectorTool): + Optional. The Integration Connector tool. + + This field is a member of `oneof`_ ``tool_type``. + data_store_tool (google.cloud.ces_v1beta.types.DataStoreTool): + Optional. The data store tool. + + This field is a member of `oneof`_ ``tool_type``. + python_function (google.cloud.ces_v1beta.types.PythonFunction): + Optional. The python function tool. + + This field is a member of `oneof`_ ``tool_type``. + mcp_tool (google.cloud.ces_v1beta.types.McpTool): + Optional. The MCP tool. An MCP tool cannot be + created or updated directly and is managed by + the MCP toolset. + + This field is a member of `oneof`_ ``tool_type``. + file_search_tool (google.cloud.ces_v1beta.types.FileSearchTool): + Optional. The file search tool. + + This field is a member of `oneof`_ ``tool_type``. + system_tool (google.cloud.ces_v1beta.types.SystemTool): + Optional. The system tool. + + This field is a member of `oneof`_ ``tool_type``. + widget_tool (google.cloud.ces_v1beta.types.WidgetTool): + Optional. The widget tool. + + This field is a member of `oneof`_ ``tool_type``. + name (str): + Identifier. The unique identifier of the tool. Format: + + - ``projects/{project}/locations/{location}/apps/{app}/tools/{tool}`` + for + + standalone tools. + ----------------- + + ``projects/{project}/locations/{location}/apps/{app}/toolsets/{toolset}/tools/{tool}`` + for tools retrieved from a toolset. These tools are dynamic + and output-only, they cannot be referenced directly where a + tool is expected. + display_name (str): + Output only. The display name of the tool, derived based on + the tool's type. For example, display name of a + [ClientFunction][Tool.ClientFunction] is derived from its + ``name`` property. + execution_type (google.cloud.ces_v1beta.types.ExecutionType): + Optional. The execution type of the tool. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the tool was + created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the tool was last + updated. + etag (str): + Etag used to ensure the object hasn't changed + during a read-modify-write operation. If the + etag is empty, the update will overwrite any + concurrent changes. + generated_summary (str): + Output only. If the tool is generated by the + LLM assistant, this field contains a descriptive + summary of the generation. + tool_fake_config (google.cloud.ces_v1beta.types.ToolFakeConfig): + Optional. Configuration for tool behavior in + fake mode. + """ + + client_function: gcc_client_function.ClientFunction = proto.Field( + proto.MESSAGE, + number=2, + oneof="tool_type", + message=gcc_client_function.ClientFunction, + ) + open_api_tool: gcc_open_api_tool.OpenApiTool = proto.Field( + proto.MESSAGE, + number=3, + oneof="tool_type", + message=gcc_open_api_tool.OpenApiTool, + ) + google_search_tool: gcc_google_search_tool.GoogleSearchTool = proto.Field( + proto.MESSAGE, + number=5, + oneof="tool_type", + message=gcc_google_search_tool.GoogleSearchTool, + ) + connector_tool: gcc_connector_tool.ConnectorTool = proto.Field( + proto.MESSAGE, + number=8, + oneof="tool_type", + message=gcc_connector_tool.ConnectorTool, + ) + data_store_tool: gcc_data_store_tool.DataStoreTool = proto.Field( + proto.MESSAGE, + number=10, + oneof="tool_type", + message=gcc_data_store_tool.DataStoreTool, + ) + python_function: gcc_python_function.PythonFunction = proto.Field( + proto.MESSAGE, + number=11, + oneof="tool_type", + message=gcc_python_function.PythonFunction, + ) + mcp_tool: gcc_mcp_tool.McpTool = proto.Field( + proto.MESSAGE, + number=16, + oneof="tool_type", + message=gcc_mcp_tool.McpTool, + ) + file_search_tool: gcc_file_search_tool.FileSearchTool = proto.Field( + proto.MESSAGE, + number=17, + oneof="tool_type", + message=gcc_file_search_tool.FileSearchTool, + ) + system_tool: gcc_system_tool.SystemTool = proto.Field( + proto.MESSAGE, + number=18, + oneof="tool_type", + message=gcc_system_tool.SystemTool, + ) + widget_tool: gcc_widget_tool.WidgetTool = proto.Field( + proto.MESSAGE, + number=24, + oneof="tool_type", + message=gcc_widget_tool.WidgetTool, + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=13, + ) + execution_type: common.ExecutionType = proto.Field( + proto.ENUM, + number=12, + enum=common.ExecutionType, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + etag: str = proto.Field( + proto.STRING, + number=14, + ) + generated_summary: str = proto.Field( + proto.STRING, + number=15, + ) + tool_fake_config: fakes.ToolFakeConfig = proto.Field( + proto.MESSAGE, + number=20, + message=fakes.ToolFakeConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/tool_service.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/tool_service.py new file mode 100644 index 000000000000..e9acb2b758b3 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/tool_service.py @@ -0,0 +1,301 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import google.protobuf.struct_pb2 as struct_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.ces_v1beta.types import schema +from google.cloud.ces_v1beta.types import tool as gcc_tool +from google.cloud.ces_v1beta.types import toolset_tool as gcc_toolset_tool + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "ExecuteToolRequest", + "ExecuteToolResponse", + "RetrieveToolSchemaRequest", + "RetrieveToolSchemaResponse", + "RetrieveToolsRequest", + "RetrieveToolsResponse", + }, +) + + +class ExecuteToolRequest(proto.Message): + r"""Request message for + [ToolService.ExecuteTool][google.cloud.ces.v1beta.ToolService.ExecuteTool]. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + tool (str): + Optional. The name of the tool to execute. + Format: + + projects/{project}/locations/{location}/apps/{app}/tools/{tool} + + This field is a member of `oneof`_ ``tool_identifier``. + toolset_tool (google.cloud.ces_v1beta.types.ToolsetTool): + Optional. The toolset tool to execute. Only + one tool should match the predicate from the + toolset. Otherwise, an error will be returned. + + This field is a member of `oneof`_ ``tool_identifier``. + parent (str): + Required. The resource name of the app which the + tool/toolset belongs to. Format: + ``projects/{project}/locations/{location}/apps/{app}`` + args (google.protobuf.struct_pb2.Struct): + Optional. The input parameters and values for + the tool in JSON object format. + variables (google.protobuf.struct_pb2.Struct): + Optional. The variables that are available + for the tool execution. + """ + + tool: str = proto.Field( + proto.STRING, + number=1, + oneof="tool_identifier", + ) + toolset_tool: gcc_toolset_tool.ToolsetTool = proto.Field( + proto.MESSAGE, + number=3, + oneof="tool_identifier", + message=gcc_toolset_tool.ToolsetTool, + ) + parent: str = proto.Field( + proto.STRING, + number=4, + ) + args: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=2, + message=struct_pb2.Struct, + ) + variables: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=5, + message=struct_pb2.Struct, + ) + + +class ExecuteToolResponse(proto.Message): + r"""Response message for + [ToolService.ExecuteTool][google.cloud.ces.v1beta.ToolService.ExecuteTool]. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + tool (str): + The name of the tool that got executed. Format: + ``projects/{project}/locations/{location}/apps/{app}/tools/{tool}`` + + This field is a member of `oneof`_ ``tool_identifier``. + toolset_tool (google.cloud.ces_v1beta.types.ToolsetTool): + The toolset tool that got executed. + + This field is a member of `oneof`_ ``tool_identifier``. + response (google.protobuf.struct_pb2.Struct): + The tool execution result in JSON object + format. Use "output" key to specify tool + response and "error" key to specify error + details (if any). If "output" and "error" keys + are not specified, then whole "response" is + treated as tool execution result. + variables (google.protobuf.struct_pb2.Struct): + The variable values at the end of the tool + execution. + """ + + tool: str = proto.Field( + proto.STRING, + number=1, + oneof="tool_identifier", + ) + toolset_tool: gcc_toolset_tool.ToolsetTool = proto.Field( + proto.MESSAGE, + number=3, + oneof="tool_identifier", + message=gcc_toolset_tool.ToolsetTool, + ) + response: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=2, + message=struct_pb2.Struct, + ) + variables: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=4, + message=struct_pb2.Struct, + ) + + +class RetrieveToolSchemaRequest(proto.Message): + r"""Request message for + [ToolService.RetrieveToolSchema][google.cloud.ces.v1beta.ToolService.RetrieveToolSchema]. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + tool (str): + Optional. The name of the tool to retrieve + the schema for. Format: + + projects/{project}/locations/{location}/apps/{app}/tools/{tool} + + This field is a member of `oneof`_ ``tool_identifier``. + toolset_tool (google.cloud.ces_v1beta.types.ToolsetTool): + Optional. The toolset tool to retrieve the + schema for. Only one tool should match the + predicate from the toolset. Otherwise, an error + will be returned. + + This field is a member of `oneof`_ ``tool_identifier``. + parent (str): + Required. The resource name of the app which the + tool/toolset belongs to. Format: + ``projects/{project}/locations/{location}/apps/{app}`` + """ + + tool: str = proto.Field( + proto.STRING, + number=1, + oneof="tool_identifier", + ) + toolset_tool: gcc_toolset_tool.ToolsetTool = proto.Field( + proto.MESSAGE, + number=2, + oneof="tool_identifier", + message=gcc_toolset_tool.ToolsetTool, + ) + parent: str = proto.Field( + proto.STRING, + number=3, + ) + + +class RetrieveToolSchemaResponse(proto.Message): + r"""Response message for + [ToolService.RetrieveToolSchema][google.cloud.ces.v1beta.ToolService.RetrieveToolSchema]. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + tool (str): + The name of the tool that the schema is for. Format: + ``projects/{project}/locations/{location}/apps/{app}/tools/{tool}`` + + This field is a member of `oneof`_ ``tool_identifier``. + toolset_tool (google.cloud.ces_v1beta.types.ToolsetTool): + The toolset tool that the schema is for. + + This field is a member of `oneof`_ ``tool_identifier``. + input_schema (google.cloud.ces_v1beta.types.Schema): + The schema of the tool input parameters. + output_schema (google.cloud.ces_v1beta.types.Schema): + The schema of the tool output parameters. + """ + + tool: str = proto.Field( + proto.STRING, + number=1, + oneof="tool_identifier", + ) + toolset_tool: gcc_toolset_tool.ToolsetTool = proto.Field( + proto.MESSAGE, + number=2, + oneof="tool_identifier", + message=gcc_toolset_tool.ToolsetTool, + ) + input_schema: schema.Schema = proto.Field( + proto.MESSAGE, + number=3, + message=schema.Schema, + ) + output_schema: schema.Schema = proto.Field( + proto.MESSAGE, + number=4, + message=schema.Schema, + ) + + +class RetrieveToolsRequest(proto.Message): + r"""Request message for + [ToolService.RetrieveTools][google.cloud.ces.v1beta.ToolService.RetrieveTools]. + + Attributes: + toolset (str): + Required. The name of the toolset to retrieve the tools for. + Format: + ``projects/{project}/locations/{location}/apps/{app}/toolsets/{toolset}`` + tool_ids (MutableSequence[str]): + Optional. The identifiers of the tools to + retrieve from the toolset. If empty, all tools + in the toolset will be returned. + """ + + toolset: str = proto.Field( + proto.STRING, + number=1, + ) + tool_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class RetrieveToolsResponse(proto.Message): + r"""Response message for + [ToolService.RetrieveTools][google.cloud.ces.v1beta.ToolService.RetrieveTools]. + + Attributes: + tools (MutableSequence[google.cloud.ces_v1beta.types.Tool]): + The list of tools that are included in the + specified toolset. + """ + + tools: MutableSequence[gcc_tool.Tool] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcc_tool.Tool, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/toolset.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/toolset.py new file mode 100644 index 000000000000..f47295b87924 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/toolset.py @@ -0,0 +1,146 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.ces_v1beta.types import common, fakes +from google.cloud.ces_v1beta.types import connector_toolset as gcc_connector_toolset +from google.cloud.ces_v1beta.types import mcp_toolset as gcc_mcp_toolset +from google.cloud.ces_v1beta.types import open_api_toolset as gcc_open_api_toolset + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "Toolset", + }, +) + + +class Toolset(proto.Message): + r"""A toolset represents a group of dynamically managed tools + that can be used by the agent. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + mcp_toolset (google.cloud.ces_v1beta.types.McpToolset): + Optional. A toolset that contains a list of + tools that are offered by the MCP server. + + This field is a member of `oneof`_ ``toolset_type``. + open_api_toolset (google.cloud.ces_v1beta.types.OpenApiToolset): + Optional. A toolset that contains a list of + tools that are defined by an OpenAPI schema. + + This field is a member of `oneof`_ ``toolset_type``. + connector_toolset (google.cloud.ces_v1beta.types.ConnectorToolset): + Optional. A toolset that generates tools from + an Integration Connectors Connection. + + This field is a member of `oneof`_ ``toolset_type``. + name (str): + Identifier. The unique identifier of the toolset. Format: + ``projects/{project}/locations/{location}/apps/{app}/toolsets/{toolset}`` + display_name (str): + Optional. The display name of the toolset. + Must be unique within the same app. + description (str): + Optional. The description of the toolset. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the toolset was + created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp when the toolset was + last updated. + etag (str): + ETag used to ensure the object hasn't changed + during a read-modify-write operation. If the + etag is empty, the update will overwrite any + concurrent changes. + execution_type (google.cloud.ces_v1beta.types.ExecutionType): + Optional. The execution type of the tools in + the toolset. + tool_fake_config (google.cloud.ces_v1beta.types.ToolFakeConfig): + Optional. Configuration for tools behavior in + fake mode. + """ + + mcp_toolset: gcc_mcp_toolset.McpToolset = proto.Field( + proto.MESSAGE, + number=6, + oneof="toolset_type", + message=gcc_mcp_toolset.McpToolset, + ) + open_api_toolset: gcc_open_api_toolset.OpenApiToolset = proto.Field( + proto.MESSAGE, + number=7, + oneof="toolset_type", + message=gcc_open_api_toolset.OpenApiToolset, + ) + connector_toolset: gcc_connector_toolset.ConnectorToolset = proto.Field( + proto.MESSAGE, + number=8, + oneof="toolset_type", + message=gcc_connector_toolset.ConnectorToolset, + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + description: str = proto.Field( + proto.STRING, + number=10, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + etag: str = proto.Field( + proto.STRING, + number=5, + ) + execution_type: common.ExecutionType = proto.Field( + proto.ENUM, + number=9, + enum=common.ExecutionType, + ) + tool_fake_config: fakes.ToolFakeConfig = proto.Field( + proto.MESSAGE, + number=11, + message=fakes.ToolFakeConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/toolset_tool.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/toolset_tool.py new file mode 100644 index 000000000000..0b8dde10f97e --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/toolset_tool.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "ToolsetTool", + }, +) + + +class ToolsetTool(proto.Message): + r"""A tool that is created from a toolset. + + Attributes: + toolset (str): + Required. The resource name of the Toolset from which this + tool is derived. Format: + ``projects/{project}/locations/{location}/apps/{app}/toolsets/{toolset}`` + tool_id (str): + Optional. The tool ID to filter the tools to + retrieve the schema for. + """ + + toolset: str = proto.Field( + proto.STRING, + number=1, + ) + tool_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/widget_service.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/widget_service.py new file mode 100644 index 000000000000..5e50c64d7ed8 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/widget_service.py @@ -0,0 +1,89 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "GenerateChatTokenRequest", + "GenerateChatTokenResponse", + }, +) + + +class GenerateChatTokenRequest(proto.Message): + r"""Request message for + [WidgetService.GenerateChatToken][google.cloud.ces.v1beta.WidgetService.GenerateChatToken]. + + Attributes: + name (str): + Required. The session name to generate the + chat token for. Format: + + projects/{project}/locations/{location}/apps/{app}/sessions/{session} + deployment (str): + Required. The deployment of the app to use + for the session. Format: + + projects/{project}/locations/{location}/apps/{app}/deployments/{deployment} + recaptcha_token (str): + Optional. The reCAPTCHA token generated by + the client-side chat widget. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + deployment: str = proto.Field( + proto.STRING, + number=2, + ) + recaptcha_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class GenerateChatTokenResponse(proto.Message): + r"""Response message for + [WidgetService.GenerateChatToken][google.cloud.ces.v1beta.WidgetService.GenerateChatToken]. + + Attributes: + chat_token (str): + The session scoped token for chat widget to + authenticate with Session APIs. + expire_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the chat token expires. + """ + + chat_token: str = proto.Field( + proto.STRING, + number=1, + ) + expire_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/google/cloud/ces_v1beta/types/widget_tool.py b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/widget_tool.py new file mode 100644 index 000000000000..df7c27913f36 --- /dev/null +++ b/packages/google-cloud-ces/google/cloud/ces_v1beta/types/widget_tool.py @@ -0,0 +1,126 @@ +# -*- coding: utf-8 -*- +# 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 typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.ces_v1beta.types import schema + +__protobuf__ = proto.module( + package="google.cloud.ces.v1beta", + manifest={ + "WidgetTool", + }, +) + + +class WidgetTool(proto.Message): + r"""Represents a widget tool that the agent can invoke. When the + tool is chosen by the agent, agent will return the widget to the + client. The client is responsible for processing the widget and + generating the next user query to continue the interaction with + the agent. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parameters (google.cloud.ces_v1beta.types.Schema): + Optional. The input parameters of the widget + tool. + + This field is a member of `oneof`_ ``input``. + name (str): + Required. The display name of the widget + tool. + description (str): + Optional. The description of the widget tool. + widget_type (google.cloud.ces_v1beta.types.WidgetTool.WidgetType): + Optional. The type of the widget tool. If not + specified, the default type will be CUSTOMIZED. + """ + + class WidgetType(proto.Enum): + r"""All available widget types. + New values may be added to this enum in the future. + + Values: + WIDGET_TYPE_UNSPECIFIED (0): + Unspecified widget type. + CUSTOM (1): + Custom widget type. + PRODUCT_CAROUSEL (2): + Product carousel widget. + PRODUCT_DETAILS (3): + Product details widget. + QUICK_ACTIONS (4): + Quick actions widget. + PRODUCT_COMPARISON (5): + Product comparison widget. + ADVANCED_PRODUCT_DETAILS (6): + Advanced product details widget. + SHORT_FORM (7): + Short form widget. + OVERALL_SATISFACTION (8): + Overall satisfaction widget. + ORDER_SUMMARY (9): + Order summary widget. + APPOINTMENT_DETAILS (10): + Appointment details widget. + APPOINTMENT_SCHEDULER (11): + Appointment scheduler widget. + CONTACT_FORM (12): + Contact form widget. + """ + + WIDGET_TYPE_UNSPECIFIED = 0 + CUSTOM = 1 + PRODUCT_CAROUSEL = 2 + PRODUCT_DETAILS = 3 + QUICK_ACTIONS = 4 + PRODUCT_COMPARISON = 5 + ADVANCED_PRODUCT_DETAILS = 6 + SHORT_FORM = 7 + OVERALL_SATISFACTION = 8 + ORDER_SUMMARY = 9 + APPOINTMENT_DETAILS = 10 + APPOINTMENT_SCHEDULER = 11 + CONTACT_FORM = 12 + + parameters: schema.Schema = proto.Field( + proto.MESSAGE, + number=4, + oneof="input", + message=schema.Schema, + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + widget_type: WidgetType = proto.Field( + proto.ENUM, + number=3, + enum=WidgetType, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_batch_delete_conversations_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_batch_delete_conversations_async.py new file mode 100644 index 000000000000..82196a8d9d9e --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_batch_delete_conversations_async.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchDeleteConversations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_BatchDeleteConversations_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_batch_delete_conversations(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.BatchDeleteConversationsRequest( + parent="parent_value", + conversations=["conversations_value1", "conversations_value2"], + ) + + # Make the request + operation = client.batch_delete_conversations(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_BatchDeleteConversations_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_batch_delete_conversations_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_batch_delete_conversations_sync.py new file mode 100644 index 000000000000..a1ecb728532f --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_batch_delete_conversations_sync.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchDeleteConversations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_BatchDeleteConversations_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_batch_delete_conversations(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.BatchDeleteConversationsRequest( + parent="parent_value", + conversations=["conversations_value1", "conversations_value2"], + ) + + # Make the request + operation = client.batch_delete_conversations(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_BatchDeleteConversations_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_agent_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_agent_async.py new file mode 100644 index 000000000000..dee8f560e9db --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_agent_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAgent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_CreateAgent_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_create_agent(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + agent = ces_v1beta.Agent() + agent.display_name = "display_name_value" + + request = ces_v1beta.CreateAgentRequest( + parent="parent_value", + agent=agent, + ) + + # Make the request + response = await client.create_agent(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_CreateAgent_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_agent_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_agent_sync.py new file mode 100644 index 000000000000..40ca25f39959 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_agent_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAgent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_CreateAgent_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_create_agent(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + agent = ces_v1beta.Agent() + agent.display_name = "display_name_value" + + request = ces_v1beta.CreateAgentRequest( + parent="parent_value", + agent=agent, + ) + + # Make the request + response = client.create_agent(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_CreateAgent_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_app_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_app_async.py new file mode 100644 index 000000000000..4bad94a9f4d9 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_app_async.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateApp +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_CreateApp_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_create_app(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + app = ces_v1beta.App() + app.display_name = "display_name_value" + + request = ces_v1beta.CreateAppRequest( + parent="parent_value", + app=app, + ) + + # Make the request + operation = client.create_app(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_CreateApp_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_app_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_app_sync.py new file mode 100644 index 000000000000..33e75d6213c5 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_app_sync.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateApp +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_CreateApp_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_create_app(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + app = ces_v1beta.App() + app.display_name = "display_name_value" + + request = ces_v1beta.CreateAppRequest( + parent="parent_value", + app=app, + ) + + # Make the request + operation = client.create_app(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_CreateApp_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_app_version_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_app_version_async.py new file mode 100644 index 000000000000..e34540dd79f0 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_app_version_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAppVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_CreateAppVersion_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_create_app_version(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.CreateAppVersionRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_app_version(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_CreateAppVersion_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_app_version_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_app_version_sync.py new file mode 100644 index 000000000000..58322c024727 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_app_version_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateAppVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_CreateAppVersion_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_create_app_version(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.CreateAppVersionRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_app_version(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_CreateAppVersion_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_deployment_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_deployment_async.py new file mode 100644 index 000000000000..e5fc8cac3043 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_deployment_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateDeployment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_CreateDeployment_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_create_deployment(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + deployment = ces_v1beta.Deployment() + deployment.display_name = "display_name_value" + + request = ces_v1beta.CreateDeploymentRequest( + parent="parent_value", + deployment=deployment, + ) + + # Make the request + response = await client.create_deployment(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_CreateDeployment_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_deployment_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_deployment_sync.py new file mode 100644 index 000000000000..9ff44b769199 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_deployment_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateDeployment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_CreateDeployment_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_create_deployment(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + deployment = ces_v1beta.Deployment() + deployment.display_name = "display_name_value" + + request = ces_v1beta.CreateDeploymentRequest( + parent="parent_value", + deployment=deployment, + ) + + # Make the request + response = client.create_deployment(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_CreateDeployment_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_example_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_example_async.py new file mode 100644 index 000000000000..69453817f6a2 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_example_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateExample +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_CreateExample_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_create_example(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + example = ces_v1beta.Example() + example.display_name = "display_name_value" + + request = ces_v1beta.CreateExampleRequest( + parent="parent_value", + example=example, + ) + + # Make the request + response = await client.create_example(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_CreateExample_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_example_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_example_sync.py new file mode 100644 index 000000000000..23a4fe6dc016 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_example_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateExample +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_CreateExample_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_create_example(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + example = ces_v1beta.Example() + example.display_name = "display_name_value" + + request = ces_v1beta.CreateExampleRequest( + parent="parent_value", + example=example, + ) + + # Make the request + response = client.create_example(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_CreateExample_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_guardrail_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_guardrail_async.py new file mode 100644 index 000000000000..880eaf39a1e7 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_guardrail_async.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateGuardrail +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_CreateGuardrail_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_create_guardrail(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + guardrail = ces_v1beta.Guardrail() + guardrail.content_filter.match_type = "REGEXP_MATCH" + guardrail.display_name = "display_name_value" + + request = ces_v1beta.CreateGuardrailRequest( + parent="parent_value", + guardrail=guardrail, + ) + + # Make the request + response = await client.create_guardrail(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_CreateGuardrail_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_guardrail_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_guardrail_sync.py new file mode 100644 index 000000000000..7bffae8ef95e --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_guardrail_sync.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateGuardrail +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_CreateGuardrail_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_create_guardrail(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + guardrail = ces_v1beta.Guardrail() + guardrail.content_filter.match_type = "REGEXP_MATCH" + guardrail.display_name = "display_name_value" + + request = ces_v1beta.CreateGuardrailRequest( + parent="parent_value", + guardrail=guardrail, + ) + + # Make the request + response = client.create_guardrail(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_CreateGuardrail_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_tool_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_tool_async.py new file mode 100644 index 000000000000..a03e3d99d144 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_tool_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateTool +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_CreateTool_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_create_tool(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + tool = ces_v1beta.Tool() + tool.client_function.name = "name_value" + + request = ces_v1beta.CreateToolRequest( + parent="parent_value", + tool=tool, + ) + + # Make the request + response = await client.create_tool(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_CreateTool_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_tool_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_tool_sync.py new file mode 100644 index 000000000000..f7497d2d3511 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_tool_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateTool +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_CreateTool_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_create_tool(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + tool = ces_v1beta.Tool() + tool.client_function.name = "name_value" + + request = ces_v1beta.CreateToolRequest( + parent="parent_value", + tool=tool, + ) + + # Make the request + response = client.create_tool(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_CreateTool_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_toolset_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_toolset_async.py new file mode 100644 index 000000000000..d7b2b29b7ea2 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_toolset_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateToolset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_CreateToolset_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_create_toolset(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + toolset = ces_v1beta.Toolset() + toolset.mcp_toolset.server_address = "server_address_value" + + request = ces_v1beta.CreateToolsetRequest( + parent="parent_value", + toolset=toolset, + ) + + # Make the request + response = await client.create_toolset(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_CreateToolset_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_toolset_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_toolset_sync.py new file mode 100644 index 000000000000..ed7225d87cfa --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_create_toolset_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateToolset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_CreateToolset_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_create_toolset(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + toolset = ces_v1beta.Toolset() + toolset.mcp_toolset.server_address = "server_address_value" + + request = ces_v1beta.CreateToolsetRequest( + parent="parent_value", + toolset=toolset, + ) + + # Make the request + response = client.create_toolset(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_CreateToolset_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_agent_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_agent_async.py new file mode 100644 index 000000000000..deb61c6c8273 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_agent_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteAgent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_DeleteAgent_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_delete_agent(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteAgentRequest( + name="name_value", + ) + + # Make the request + await client.delete_agent(request=request) + + +# [END ces_v1beta_generated_AgentService_DeleteAgent_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_agent_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_agent_sync.py new file mode 100644 index 000000000000..1e86e1ee36a5 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_agent_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteAgent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_DeleteAgent_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_delete_agent(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteAgentRequest( + name="name_value", + ) + + # Make the request + client.delete_agent(request=request) + + +# [END ces_v1beta_generated_AgentService_DeleteAgent_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_app_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_app_async.py new file mode 100644 index 000000000000..888e39c059af --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_app_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteApp +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_DeleteApp_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_delete_app(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteAppRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_app(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_DeleteApp_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_app_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_app_sync.py new file mode 100644 index 000000000000..6d7dc109e759 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_app_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteApp +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_DeleteApp_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_delete_app(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteAppRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_app(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_DeleteApp_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_app_version_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_app_version_async.py new file mode 100644 index 000000000000..ddb067b1b109 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_app_version_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteAppVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_DeleteAppVersion_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_delete_app_version(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteAppVersionRequest( + name="name_value", + ) + + # Make the request + await client.delete_app_version(request=request) + + +# [END ces_v1beta_generated_AgentService_DeleteAppVersion_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_app_version_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_app_version_sync.py new file mode 100644 index 000000000000..f30d474df6b1 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_app_version_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteAppVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_DeleteAppVersion_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_delete_app_version(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteAppVersionRequest( + name="name_value", + ) + + # Make the request + client.delete_app_version(request=request) + + +# [END ces_v1beta_generated_AgentService_DeleteAppVersion_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_conversation_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_conversation_async.py new file mode 100644 index 000000000000..cfe64f69e3e0 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_conversation_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteConversation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_DeleteConversation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_delete_conversation(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteConversationRequest( + name="name_value", + ) + + # Make the request + await client.delete_conversation(request=request) + + +# [END ces_v1beta_generated_AgentService_DeleteConversation_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_conversation_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_conversation_sync.py new file mode 100644 index 000000000000..28820544a77b --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_conversation_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteConversation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_DeleteConversation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_delete_conversation(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteConversationRequest( + name="name_value", + ) + + # Make the request + client.delete_conversation(request=request) + + +# [END ces_v1beta_generated_AgentService_DeleteConversation_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_deployment_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_deployment_async.py new file mode 100644 index 000000000000..861af06f9390 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_deployment_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteDeployment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_DeleteDeployment_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_delete_deployment(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteDeploymentRequest( + name="name_value", + ) + + # Make the request + await client.delete_deployment(request=request) + + +# [END ces_v1beta_generated_AgentService_DeleteDeployment_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_deployment_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_deployment_sync.py new file mode 100644 index 000000000000..30dd6998f24e --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_deployment_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteDeployment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_DeleteDeployment_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_delete_deployment(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteDeploymentRequest( + name="name_value", + ) + + # Make the request + client.delete_deployment(request=request) + + +# [END ces_v1beta_generated_AgentService_DeleteDeployment_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_example_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_example_async.py new file mode 100644 index 000000000000..2803a20c4497 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_example_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteExample +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_DeleteExample_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_delete_example(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteExampleRequest( + name="name_value", + ) + + # Make the request + await client.delete_example(request=request) + + +# [END ces_v1beta_generated_AgentService_DeleteExample_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_example_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_example_sync.py new file mode 100644 index 000000000000..3d191d9c728e --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_example_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteExample +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_DeleteExample_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_delete_example(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteExampleRequest( + name="name_value", + ) + + # Make the request + client.delete_example(request=request) + + +# [END ces_v1beta_generated_AgentService_DeleteExample_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_guardrail_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_guardrail_async.py new file mode 100644 index 000000000000..173d22b0b201 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_guardrail_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteGuardrail +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_DeleteGuardrail_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_delete_guardrail(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteGuardrailRequest( + name="name_value", + ) + + # Make the request + await client.delete_guardrail(request=request) + + +# [END ces_v1beta_generated_AgentService_DeleteGuardrail_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_guardrail_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_guardrail_sync.py new file mode 100644 index 000000000000..9dec2479fae4 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_guardrail_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteGuardrail +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_DeleteGuardrail_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_delete_guardrail(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteGuardrailRequest( + name="name_value", + ) + + # Make the request + client.delete_guardrail(request=request) + + +# [END ces_v1beta_generated_AgentService_DeleteGuardrail_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_tool_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_tool_async.py new file mode 100644 index 000000000000..57165194c2c4 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_tool_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteTool +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_DeleteTool_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_delete_tool(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteToolRequest( + name="name_value", + ) + + # Make the request + await client.delete_tool(request=request) + + +# [END ces_v1beta_generated_AgentService_DeleteTool_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_tool_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_tool_sync.py new file mode 100644 index 000000000000..3410c7f26253 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_tool_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteTool +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_DeleteTool_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_delete_tool(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteToolRequest( + name="name_value", + ) + + # Make the request + client.delete_tool(request=request) + + +# [END ces_v1beta_generated_AgentService_DeleteTool_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_toolset_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_toolset_async.py new file mode 100644 index 000000000000..54777dac057e --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_toolset_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteToolset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_DeleteToolset_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_delete_toolset(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteToolsetRequest( + name="name_value", + ) + + # Make the request + await client.delete_toolset(request=request) + + +# [END ces_v1beta_generated_AgentService_DeleteToolset_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_toolset_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_toolset_sync.py new file mode 100644 index 000000000000..7938aafffa10 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_delete_toolset_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteToolset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_DeleteToolset_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_delete_toolset(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteToolsetRequest( + name="name_value", + ) + + # Make the request + client.delete_toolset(request=request) + + +# [END ces_v1beta_generated_AgentService_DeleteToolset_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_export_app_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_export_app_async.py new file mode 100644 index 000000000000..3054788814e1 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_export_app_async.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ExportApp +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_ExportApp_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_export_app(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ExportAppRequest( + name="name_value", + export_format="YAML", + ) + + # Make the request + operation = client.export_app(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_ExportApp_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_export_app_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_export_app_sync.py new file mode 100644 index 000000000000..b04341e6d7b4 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_export_app_sync.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ExportApp +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_ExportApp_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_export_app(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ExportAppRequest( + name="name_value", + export_format="YAML", + ) + + # Make the request + operation = client.export_app(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_ExportApp_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_agent_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_agent_async.py new file mode 100644 index 000000000000..8760f5ab7569 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_agent_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAgent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_GetAgent_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_get_agent(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.GetAgentRequest( + name="name_value", + ) + + # Make the request + response = await client.get_agent(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_GetAgent_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_agent_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_agent_sync.py new file mode 100644 index 000000000000..c18dfbed73ab --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_agent_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAgent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_GetAgent_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_get_agent(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.GetAgentRequest( + name="name_value", + ) + + # Make the request + response = client.get_agent(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_GetAgent_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_app_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_app_async.py new file mode 100644 index 000000000000..c29a11f078e4 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_app_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetApp +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_GetApp_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_get_app(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.GetAppRequest( + name="name_value", + ) + + # Make the request + response = await client.get_app(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_GetApp_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_app_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_app_sync.py new file mode 100644 index 000000000000..e2fc189ccc31 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_app_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetApp +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_GetApp_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_get_app(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.GetAppRequest( + name="name_value", + ) + + # Make the request + response = client.get_app(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_GetApp_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_app_version_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_app_version_async.py new file mode 100644 index 000000000000..741b810aceb1 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_app_version_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAppVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_GetAppVersion_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_get_app_version(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.GetAppVersionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_app_version(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_GetAppVersion_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_app_version_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_app_version_sync.py new file mode 100644 index 000000000000..6e5236a98dfd --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_app_version_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAppVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_GetAppVersion_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_get_app_version(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.GetAppVersionRequest( + name="name_value", + ) + + # Make the request + response = client.get_app_version(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_GetAppVersion_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_changelog_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_changelog_async.py new file mode 100644 index 000000000000..6e0b5c6294b6 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_changelog_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetChangelog +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_GetChangelog_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_get_changelog(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.GetChangelogRequest( + name="name_value", + ) + + # Make the request + response = await client.get_changelog(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_GetChangelog_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_changelog_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_changelog_sync.py new file mode 100644 index 000000000000..29d08f498228 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_changelog_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetChangelog +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_GetChangelog_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_get_changelog(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.GetChangelogRequest( + name="name_value", + ) + + # Make the request + response = client.get_changelog(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_GetChangelog_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_conversation_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_conversation_async.py new file mode 100644 index 000000000000..e958990d5574 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_conversation_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetConversation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_GetConversation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_get_conversation(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.GetConversationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_conversation(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_GetConversation_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_conversation_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_conversation_sync.py new file mode 100644 index 000000000000..56c34bbd6f74 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_conversation_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetConversation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_GetConversation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_get_conversation(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.GetConversationRequest( + name="name_value", + ) + + # Make the request + response = client.get_conversation(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_GetConversation_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_deployment_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_deployment_async.py new file mode 100644 index 000000000000..3a6529cf11d0 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_deployment_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDeployment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_GetDeployment_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_get_deployment(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.GetDeploymentRequest( + name="name_value", + ) + + # Make the request + response = await client.get_deployment(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_GetDeployment_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_deployment_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_deployment_sync.py new file mode 100644 index 000000000000..13513f4ccbe5 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_deployment_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetDeployment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_GetDeployment_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_get_deployment(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.GetDeploymentRequest( + name="name_value", + ) + + # Make the request + response = client.get_deployment(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_GetDeployment_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_example_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_example_async.py new file mode 100644 index 000000000000..65581521866f --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_example_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetExample +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_GetExample_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_get_example(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.GetExampleRequest( + name="name_value", + ) + + # Make the request + response = await client.get_example(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_GetExample_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_example_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_example_sync.py new file mode 100644 index 000000000000..c057f0ebed49 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_example_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetExample +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_GetExample_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_get_example(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.GetExampleRequest( + name="name_value", + ) + + # Make the request + response = client.get_example(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_GetExample_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_guardrail_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_guardrail_async.py new file mode 100644 index 000000000000..a63f4676dcac --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_guardrail_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetGuardrail +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_GetGuardrail_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_get_guardrail(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.GetGuardrailRequest( + name="name_value", + ) + + # Make the request + response = await client.get_guardrail(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_GetGuardrail_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_guardrail_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_guardrail_sync.py new file mode 100644 index 000000000000..e80437c2dbd5 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_guardrail_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetGuardrail +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_GetGuardrail_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_get_guardrail(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.GetGuardrailRequest( + name="name_value", + ) + + # Make the request + response = client.get_guardrail(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_GetGuardrail_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_tool_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_tool_async.py new file mode 100644 index 000000000000..fbe6f07e98cc --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_tool_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetTool +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_GetTool_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_get_tool(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.GetToolRequest( + name="name_value", + ) + + # Make the request + response = await client.get_tool(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_GetTool_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_tool_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_tool_sync.py new file mode 100644 index 000000000000..504e78581a6c --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_tool_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetTool +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_GetTool_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_get_tool(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.GetToolRequest( + name="name_value", + ) + + # Make the request + response = client.get_tool(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_GetTool_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_toolset_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_toolset_async.py new file mode 100644 index 000000000000..df8c9aca5463 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_toolset_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetToolset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_GetToolset_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_get_toolset(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.GetToolsetRequest( + name="name_value", + ) + + # Make the request + response = await client.get_toolset(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_GetToolset_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_toolset_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_toolset_sync.py new file mode 100644 index 000000000000..2f2870f5219c --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_get_toolset_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetToolset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_GetToolset_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_get_toolset(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.GetToolsetRequest( + name="name_value", + ) + + # Make the request + response = client.get_toolset(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_GetToolset_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_import_app_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_import_app_async.py new file mode 100644 index 000000000000..b32620f251d4 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_import_app_async.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportApp +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_ImportApp_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_import_app(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ImportAppRequest( + gcs_uri="gcs_uri_value", + parent="parent_value", + ) + + # Make the request + operation = client.import_app(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_ImportApp_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_import_app_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_import_app_sync.py new file mode 100644 index 000000000000..229ff86f188f --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_import_app_sync.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportApp +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_ImportApp_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_import_app(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ImportAppRequest( + gcs_uri="gcs_uri_value", + parent="parent_value", + ) + + # Make the request + operation = client.import_app(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_ImportApp_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_agents_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_agents_async.py new file mode 100644 index 000000000000..0153cd4e0882 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_agents_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAgents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_ListAgents_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_list_agents(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ListAgentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_agents(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END ces_v1beta_generated_AgentService_ListAgents_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_agents_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_agents_sync.py new file mode 100644 index 000000000000..b160ca45ee56 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_agents_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAgents +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_ListAgents_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_list_agents(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ListAgentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_agents(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END ces_v1beta_generated_AgentService_ListAgents_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_app_versions_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_app_versions_async.py new file mode 100644 index 000000000000..0a748ccffcf5 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_app_versions_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAppVersions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_ListAppVersions_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_list_app_versions(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ListAppVersionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_app_versions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END ces_v1beta_generated_AgentService_ListAppVersions_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_app_versions_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_app_versions_sync.py new file mode 100644 index 000000000000..30e21c52d983 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_app_versions_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListAppVersions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_ListAppVersions_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_list_app_versions(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ListAppVersionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_app_versions(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END ces_v1beta_generated_AgentService_ListAppVersions_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_apps_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_apps_async.py new file mode 100644 index 000000000000..998e542713c2 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_apps_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListApps +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_ListApps_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_list_apps(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ListAppsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_apps(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END ces_v1beta_generated_AgentService_ListApps_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_apps_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_apps_sync.py new file mode 100644 index 000000000000..f099e47c6aed --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_apps_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListApps +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_ListApps_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_list_apps(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ListAppsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_apps(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END ces_v1beta_generated_AgentService_ListApps_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_changelogs_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_changelogs_async.py new file mode 100644 index 000000000000..f444e6ca9a8e --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_changelogs_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListChangelogs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_ListChangelogs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_list_changelogs(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ListChangelogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_changelogs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END ces_v1beta_generated_AgentService_ListChangelogs_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_changelogs_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_changelogs_sync.py new file mode 100644 index 000000000000..d43c32fa0c31 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_changelogs_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListChangelogs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_ListChangelogs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_list_changelogs(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ListChangelogsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_changelogs(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END ces_v1beta_generated_AgentService_ListChangelogs_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_conversations_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_conversations_async.py new file mode 100644 index 000000000000..aacc2410e7c0 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_conversations_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListConversations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_ListConversations_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_list_conversations(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ListConversationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_conversations(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END ces_v1beta_generated_AgentService_ListConversations_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_conversations_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_conversations_sync.py new file mode 100644 index 000000000000..530848df277d --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_conversations_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListConversations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_ListConversations_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_list_conversations(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ListConversationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_conversations(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END ces_v1beta_generated_AgentService_ListConversations_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_deployments_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_deployments_async.py new file mode 100644 index 000000000000..b91650e9de19 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_deployments_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListDeployments +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_ListDeployments_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_list_deployments(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ListDeploymentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_deployments(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END ces_v1beta_generated_AgentService_ListDeployments_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_deployments_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_deployments_sync.py new file mode 100644 index 000000000000..e4e077ac6a31 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_deployments_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListDeployments +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_ListDeployments_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_list_deployments(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ListDeploymentsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_deployments(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END ces_v1beta_generated_AgentService_ListDeployments_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_examples_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_examples_async.py new file mode 100644 index 000000000000..69ef9187b8aa --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_examples_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListExamples +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_ListExamples_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_list_examples(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ListExamplesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_examples(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END ces_v1beta_generated_AgentService_ListExamples_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_examples_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_examples_sync.py new file mode 100644 index 000000000000..f31406ecf06a --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_examples_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListExamples +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_ListExamples_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_list_examples(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ListExamplesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_examples(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END ces_v1beta_generated_AgentService_ListExamples_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_guardrails_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_guardrails_async.py new file mode 100644 index 000000000000..85b1d1369d67 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_guardrails_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListGuardrails +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_ListGuardrails_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_list_guardrails(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ListGuardrailsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_guardrails(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END ces_v1beta_generated_AgentService_ListGuardrails_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_guardrails_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_guardrails_sync.py new file mode 100644 index 000000000000..fd73e4d76458 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_guardrails_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListGuardrails +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_ListGuardrails_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_list_guardrails(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ListGuardrailsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_guardrails(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END ces_v1beta_generated_AgentService_ListGuardrails_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_tools_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_tools_async.py new file mode 100644 index 000000000000..805ddb7d1f69 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_tools_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListTools +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_ListTools_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_list_tools(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ListToolsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_tools(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END ces_v1beta_generated_AgentService_ListTools_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_tools_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_tools_sync.py new file mode 100644 index 000000000000..4ed47369ce2f --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_tools_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListTools +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_ListTools_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_list_tools(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ListToolsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_tools(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END ces_v1beta_generated_AgentService_ListTools_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_toolsets_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_toolsets_async.py new file mode 100644 index 000000000000..edd9b2a30a0f --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_toolsets_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListToolsets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_ListToolsets_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_list_toolsets(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ListToolsetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_toolsets(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END ces_v1beta_generated_AgentService_ListToolsets_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_toolsets_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_toolsets_sync.py new file mode 100644 index 000000000000..0df008919df5 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_list_toolsets_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListToolsets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_ListToolsets_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_list_toolsets(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ListToolsetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_toolsets(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END ces_v1beta_generated_AgentService_ListToolsets_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_restore_app_version_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_restore_app_version_async.py new file mode 100644 index 000000000000..2c63c6689352 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_restore_app_version_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RestoreAppVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_RestoreAppVersion_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_restore_app_version(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.RestoreAppVersionRequest( + name="name_value", + ) + + # Make the request + operation = client.restore_app_version(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_RestoreAppVersion_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_restore_app_version_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_restore_app_version_sync.py new file mode 100644 index 000000000000..02fb0cc96040 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_restore_app_version_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RestoreAppVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_RestoreAppVersion_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_restore_app_version(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.RestoreAppVersionRequest( + name="name_value", + ) + + # Make the request + operation = client.restore_app_version(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_RestoreAppVersion_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_agent_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_agent_async.py new file mode 100644 index 000000000000..9eb27bd80ece --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_agent_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAgent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_UpdateAgent_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_update_agent(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + agent = ces_v1beta.Agent() + agent.display_name = "display_name_value" + + request = ces_v1beta.UpdateAgentRequest( + agent=agent, + ) + + # Make the request + response = await client.update_agent(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_UpdateAgent_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_agent_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_agent_sync.py new file mode 100644 index 000000000000..a3727dbb34e1 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_agent_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAgent +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_UpdateAgent_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_update_agent(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + agent = ces_v1beta.Agent() + agent.display_name = "display_name_value" + + request = ces_v1beta.UpdateAgentRequest( + agent=agent, + ) + + # Make the request + response = client.update_agent(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_UpdateAgent_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_app_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_app_async.py new file mode 100644 index 000000000000..3c3e0a8a7299 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_app_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateApp +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_UpdateApp_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_update_app(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + app = ces_v1beta.App() + app.display_name = "display_name_value" + + request = ces_v1beta.UpdateAppRequest( + app=app, + ) + + # Make the request + response = await client.update_app(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_UpdateApp_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_app_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_app_sync.py new file mode 100644 index 000000000000..f8297cfa8b63 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_app_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateApp +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_UpdateApp_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_update_app(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + app = ces_v1beta.App() + app.display_name = "display_name_value" + + request = ces_v1beta.UpdateAppRequest( + app=app, + ) + + # Make the request + response = client.update_app(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_UpdateApp_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_deployment_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_deployment_async.py new file mode 100644 index 000000000000..44abe11c9eaa --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_deployment_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateDeployment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_UpdateDeployment_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_update_deployment(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + deployment = ces_v1beta.Deployment() + deployment.display_name = "display_name_value" + + request = ces_v1beta.UpdateDeploymentRequest( + deployment=deployment, + ) + + # Make the request + response = await client.update_deployment(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_UpdateDeployment_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_deployment_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_deployment_sync.py new file mode 100644 index 000000000000..3ca7464ecadc --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_deployment_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateDeployment +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_UpdateDeployment_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_update_deployment(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + deployment = ces_v1beta.Deployment() + deployment.display_name = "display_name_value" + + request = ces_v1beta.UpdateDeploymentRequest( + deployment=deployment, + ) + + # Make the request + response = client.update_deployment(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_UpdateDeployment_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_example_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_example_async.py new file mode 100644 index 000000000000..e09a3a814dbf --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_example_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateExample +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_UpdateExample_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_update_example(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + example = ces_v1beta.Example() + example.display_name = "display_name_value" + + request = ces_v1beta.UpdateExampleRequest( + example=example, + ) + + # Make the request + response = await client.update_example(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_UpdateExample_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_example_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_example_sync.py new file mode 100644 index 000000000000..9df43a4ad3d8 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_example_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateExample +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_UpdateExample_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_update_example(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + example = ces_v1beta.Example() + example.display_name = "display_name_value" + + request = ces_v1beta.UpdateExampleRequest( + example=example, + ) + + # Make the request + response = client.update_example(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_UpdateExample_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_guardrail_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_guardrail_async.py new file mode 100644 index 000000000000..cea59a8b7de6 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_guardrail_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateGuardrail +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_UpdateGuardrail_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_update_guardrail(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + guardrail = ces_v1beta.Guardrail() + guardrail.content_filter.match_type = "REGEXP_MATCH" + guardrail.display_name = "display_name_value" + + request = ces_v1beta.UpdateGuardrailRequest( + guardrail=guardrail, + ) + + # Make the request + response = await client.update_guardrail(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_UpdateGuardrail_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_guardrail_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_guardrail_sync.py new file mode 100644 index 000000000000..a7488c759460 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_guardrail_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateGuardrail +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_UpdateGuardrail_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_update_guardrail(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + guardrail = ces_v1beta.Guardrail() + guardrail.content_filter.match_type = "REGEXP_MATCH" + guardrail.display_name = "display_name_value" + + request = ces_v1beta.UpdateGuardrailRequest( + guardrail=guardrail, + ) + + # Make the request + response = client.update_guardrail(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_UpdateGuardrail_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_tool_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_tool_async.py new file mode 100644 index 000000000000..1b783b3b8e53 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_tool_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateTool +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_UpdateTool_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_update_tool(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + tool = ces_v1beta.Tool() + tool.client_function.name = "name_value" + + request = ces_v1beta.UpdateToolRequest( + tool=tool, + ) + + # Make the request + response = await client.update_tool(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_UpdateTool_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_tool_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_tool_sync.py new file mode 100644 index 000000000000..32ac30657603 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_tool_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateTool +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_UpdateTool_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_update_tool(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + tool = ces_v1beta.Tool() + tool.client_function.name = "name_value" + + request = ces_v1beta.UpdateToolRequest( + tool=tool, + ) + + # Make the request + response = client.update_tool(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_UpdateTool_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_toolset_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_toolset_async.py new file mode 100644 index 000000000000..c8ce0e5783c7 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_toolset_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateToolset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_UpdateToolset_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_update_toolset(): + # Create a client + client = ces_v1beta.AgentServiceAsyncClient() + + # Initialize request argument(s) + toolset = ces_v1beta.Toolset() + toolset.mcp_toolset.server_address = "server_address_value" + + request = ces_v1beta.UpdateToolsetRequest( + toolset=toolset, + ) + + # Make the request + response = await client.update_toolset(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_UpdateToolset_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_toolset_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_toolset_sync.py new file mode 100644 index 000000000000..e744456ae9f2 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_agent_service_update_toolset_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateToolset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_AgentService_UpdateToolset_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_update_toolset(): + # Create a client + client = ces_v1beta.AgentServiceClient() + + # Initialize request argument(s) + toolset = ces_v1beta.Toolset() + toolset.mcp_toolset.server_address = "server_address_value" + + request = ces_v1beta.UpdateToolsetRequest( + toolset=toolset, + ) + + # Make the request + response = client.update_toolset(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_AgentService_UpdateToolset_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_create_evaluation_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_create_evaluation_async.py new file mode 100644 index 000000000000..fed42378f2ce --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_create_evaluation_async.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateEvaluation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_CreateEvaluation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_create_evaluation(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + evaluation = ces_v1beta.Evaluation() + evaluation.golden.turns.steps.user_input.text = "text_value" + evaluation.display_name = "display_name_value" + + request = ces_v1beta.CreateEvaluationRequest( + parent="parent_value", + evaluation=evaluation, + ) + + # Make the request + response = await client.create_evaluation(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_EvaluationService_CreateEvaluation_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_create_evaluation_dataset_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_create_evaluation_dataset_async.py new file mode 100644 index 000000000000..cd693527c68d --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_create_evaluation_dataset_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateEvaluationDataset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_CreateEvaluationDataset_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_create_evaluation_dataset(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + evaluation_dataset = ces_v1beta.EvaluationDataset() + evaluation_dataset.display_name = "display_name_value" + + request = ces_v1beta.CreateEvaluationDatasetRequest( + parent="parent_value", + evaluation_dataset=evaluation_dataset, + ) + + # Make the request + response = await client.create_evaluation_dataset(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_EvaluationService_CreateEvaluationDataset_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_create_evaluation_dataset_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_create_evaluation_dataset_sync.py new file mode 100644 index 000000000000..1885d55f51a1 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_create_evaluation_dataset_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateEvaluationDataset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_CreateEvaluationDataset_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_create_evaluation_dataset(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + evaluation_dataset = ces_v1beta.EvaluationDataset() + evaluation_dataset.display_name = "display_name_value" + + request = ces_v1beta.CreateEvaluationDatasetRequest( + parent="parent_value", + evaluation_dataset=evaluation_dataset, + ) + + # Make the request + response = client.create_evaluation_dataset(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_EvaluationService_CreateEvaluationDataset_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_create_evaluation_expectation_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_create_evaluation_expectation_async.py new file mode 100644 index 000000000000..3e24ab8b2a3b --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_create_evaluation_expectation_async.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateEvaluationExpectation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_CreateEvaluationExpectation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_create_evaluation_expectation(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + evaluation_expectation = ces_v1beta.EvaluationExpectation() + evaluation_expectation.llm_criteria.prompt = "prompt_value" + evaluation_expectation.display_name = "display_name_value" + + request = ces_v1beta.CreateEvaluationExpectationRequest( + parent="parent_value", + evaluation_expectation=evaluation_expectation, + ) + + # Make the request + response = await client.create_evaluation_expectation(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_EvaluationService_CreateEvaluationExpectation_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_create_evaluation_expectation_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_create_evaluation_expectation_sync.py new file mode 100644 index 000000000000..3b60b063a7bf --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_create_evaluation_expectation_sync.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateEvaluationExpectation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_CreateEvaluationExpectation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_create_evaluation_expectation(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + evaluation_expectation = ces_v1beta.EvaluationExpectation() + evaluation_expectation.llm_criteria.prompt = "prompt_value" + evaluation_expectation.display_name = "display_name_value" + + request = ces_v1beta.CreateEvaluationExpectationRequest( + parent="parent_value", + evaluation_expectation=evaluation_expectation, + ) + + # Make the request + response = client.create_evaluation_expectation(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_EvaluationService_CreateEvaluationExpectation_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_create_evaluation_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_create_evaluation_sync.py new file mode 100644 index 000000000000..bdc6549e88b4 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_create_evaluation_sync.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateEvaluation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_CreateEvaluation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_create_evaluation(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + evaluation = ces_v1beta.Evaluation() + evaluation.golden.turns.steps.user_input.text = "text_value" + evaluation.display_name = "display_name_value" + + request = ces_v1beta.CreateEvaluationRequest( + parent="parent_value", + evaluation=evaluation, + ) + + # Make the request + response = client.create_evaluation(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_EvaluationService_CreateEvaluation_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_create_scheduled_evaluation_run_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_create_scheduled_evaluation_run_async.py new file mode 100644 index 000000000000..837ad5a7688c --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_create_scheduled_evaluation_run_async.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateScheduledEvaluationRun +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_CreateScheduledEvaluationRun_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_create_scheduled_evaluation_run(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + scheduled_evaluation_run = ces_v1beta.ScheduledEvaluationRun() + scheduled_evaluation_run.display_name = "display_name_value" + scheduled_evaluation_run.request.app = "app_value" + scheduled_evaluation_run.scheduling_config.frequency = "BIWEEKLY" + + request = ces_v1beta.CreateScheduledEvaluationRunRequest( + parent="parent_value", + scheduled_evaluation_run=scheduled_evaluation_run, + ) + + # Make the request + response = await client.create_scheduled_evaluation_run(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_EvaluationService_CreateScheduledEvaluationRun_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_create_scheduled_evaluation_run_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_create_scheduled_evaluation_run_sync.py new file mode 100644 index 000000000000..34e56cc99208 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_create_scheduled_evaluation_run_sync.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateScheduledEvaluationRun +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_CreateScheduledEvaluationRun_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_create_scheduled_evaluation_run(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + scheduled_evaluation_run = ces_v1beta.ScheduledEvaluationRun() + scheduled_evaluation_run.display_name = "display_name_value" + scheduled_evaluation_run.request.app = "app_value" + scheduled_evaluation_run.scheduling_config.frequency = "BIWEEKLY" + + request = ces_v1beta.CreateScheduledEvaluationRunRequest( + parent="parent_value", + scheduled_evaluation_run=scheduled_evaluation_run, + ) + + # Make the request + response = client.create_scheduled_evaluation_run(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_EvaluationService_CreateScheduledEvaluationRun_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_delete_evaluation_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_delete_evaluation_async.py new file mode 100644 index 000000000000..036a8d9bf2e2 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_delete_evaluation_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteEvaluation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_DeleteEvaluation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_delete_evaluation(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteEvaluationRequest( + name="name_value", + ) + + # Make the request + await client.delete_evaluation(request=request) + + +# [END ces_v1beta_generated_EvaluationService_DeleteEvaluation_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_delete_evaluation_dataset_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_delete_evaluation_dataset_async.py new file mode 100644 index 000000000000..36038ff5365e --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_delete_evaluation_dataset_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteEvaluationDataset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_DeleteEvaluationDataset_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_delete_evaluation_dataset(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteEvaluationDatasetRequest( + name="name_value", + ) + + # Make the request + await client.delete_evaluation_dataset(request=request) + + +# [END ces_v1beta_generated_EvaluationService_DeleteEvaluationDataset_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_delete_evaluation_dataset_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_delete_evaluation_dataset_sync.py new file mode 100644 index 000000000000..d6f8e5ee52f2 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_delete_evaluation_dataset_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteEvaluationDataset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_DeleteEvaluationDataset_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_delete_evaluation_dataset(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteEvaluationDatasetRequest( + name="name_value", + ) + + # Make the request + client.delete_evaluation_dataset(request=request) + + +# [END ces_v1beta_generated_EvaluationService_DeleteEvaluationDataset_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_delete_evaluation_expectation_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_delete_evaluation_expectation_async.py new file mode 100644 index 000000000000..9e58e1fb5c1b --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_delete_evaluation_expectation_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteEvaluationExpectation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_DeleteEvaluationExpectation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_delete_evaluation_expectation(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteEvaluationExpectationRequest( + name="name_value", + ) + + # Make the request + await client.delete_evaluation_expectation(request=request) + + +# [END ces_v1beta_generated_EvaluationService_DeleteEvaluationExpectation_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_delete_evaluation_expectation_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_delete_evaluation_expectation_sync.py new file mode 100644 index 000000000000..d5c9e0a1985e --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_delete_evaluation_expectation_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteEvaluationExpectation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_DeleteEvaluationExpectation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_delete_evaluation_expectation(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteEvaluationExpectationRequest( + name="name_value", + ) + + # Make the request + client.delete_evaluation_expectation(request=request) + + +# [END ces_v1beta_generated_EvaluationService_DeleteEvaluationExpectation_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_delete_evaluation_result_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_delete_evaluation_result_async.py new file mode 100644 index 000000000000..3161ace7738e --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_delete_evaluation_result_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteEvaluationResult +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_DeleteEvaluationResult_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_delete_evaluation_result(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteEvaluationResultRequest( + name="name_value", + ) + + # Make the request + await client.delete_evaluation_result(request=request) + + +# [END ces_v1beta_generated_EvaluationService_DeleteEvaluationResult_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_delete_evaluation_result_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_delete_evaluation_result_sync.py new file mode 100644 index 000000000000..e15cd0a6ad54 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_delete_evaluation_result_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteEvaluationResult +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_DeleteEvaluationResult_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_delete_evaluation_result(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteEvaluationResultRequest( + name="name_value", + ) + + # Make the request + client.delete_evaluation_result(request=request) + + +# [END ces_v1beta_generated_EvaluationService_DeleteEvaluationResult_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_delete_evaluation_run_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_delete_evaluation_run_async.py new file mode 100644 index 000000000000..83ff8db6651b --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_delete_evaluation_run_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteEvaluationRun +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_DeleteEvaluationRun_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_delete_evaluation_run(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteEvaluationRunRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_evaluation_run(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_EvaluationService_DeleteEvaluationRun_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_delete_evaluation_run_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_delete_evaluation_run_sync.py new file mode 100644 index 000000000000..fa7e8d93a314 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_delete_evaluation_run_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteEvaluationRun +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_DeleteEvaluationRun_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_delete_evaluation_run(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteEvaluationRunRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_evaluation_run(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_EvaluationService_DeleteEvaluationRun_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_delete_evaluation_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_delete_evaluation_sync.py new file mode 100644 index 000000000000..aac8f733acee --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_delete_evaluation_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteEvaluation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_DeleteEvaluation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_delete_evaluation(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteEvaluationRequest( + name="name_value", + ) + + # Make the request + client.delete_evaluation(request=request) + + +# [END ces_v1beta_generated_EvaluationService_DeleteEvaluation_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_delete_scheduled_evaluation_run_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_delete_scheduled_evaluation_run_async.py new file mode 100644 index 000000000000..e9856adf8db0 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_delete_scheduled_evaluation_run_async.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteScheduledEvaluationRun +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_DeleteScheduledEvaluationRun_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_delete_scheduled_evaluation_run(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteScheduledEvaluationRunRequest( + name="name_value", + ) + + # Make the request + await client.delete_scheduled_evaluation_run(request=request) + + +# [END ces_v1beta_generated_EvaluationService_DeleteScheduledEvaluationRun_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_delete_scheduled_evaluation_run_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_delete_scheduled_evaluation_run_sync.py new file mode 100644 index 000000000000..057e75db300a --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_delete_scheduled_evaluation_run_sync.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeleteScheduledEvaluationRun +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_DeleteScheduledEvaluationRun_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_delete_scheduled_evaluation_run(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.DeleteScheduledEvaluationRunRequest( + name="name_value", + ) + + # Make the request + client.delete_scheduled_evaluation_run(request=request) + + +# [END ces_v1beta_generated_EvaluationService_DeleteScheduledEvaluationRun_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_generate_evaluation_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_generate_evaluation_async.py new file mode 100644 index 000000000000..618759332254 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_generate_evaluation_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateEvaluation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_GenerateEvaluation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_generate_evaluation(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.GenerateEvaluationRequest( + conversation="conversation_value", + ) + + # Make the request + operation = client.generate_evaluation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_EvaluationService_GenerateEvaluation_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_generate_evaluation_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_generate_evaluation_sync.py new file mode 100644 index 000000000000..968b4a01cc90 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_generate_evaluation_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateEvaluation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_GenerateEvaluation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_generate_evaluation(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.GenerateEvaluationRequest( + conversation="conversation_value", + ) + + # Make the request + operation = client.generate_evaluation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_EvaluationService_GenerateEvaluation_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_get_evaluation_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_get_evaluation_async.py new file mode 100644 index 000000000000..d2ca661ba6ca --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_get_evaluation_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEvaluation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_GetEvaluation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_get_evaluation(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.GetEvaluationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_evaluation(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_EvaluationService_GetEvaluation_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_get_evaluation_dataset_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_get_evaluation_dataset_async.py new file mode 100644 index 000000000000..70eae4f85b81 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_get_evaluation_dataset_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEvaluationDataset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_GetEvaluationDataset_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_get_evaluation_dataset(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.GetEvaluationDatasetRequest( + name="name_value", + ) + + # Make the request + response = await client.get_evaluation_dataset(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_EvaluationService_GetEvaluationDataset_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_get_evaluation_dataset_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_get_evaluation_dataset_sync.py new file mode 100644 index 000000000000..c50489e2a9fe --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_get_evaluation_dataset_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEvaluationDataset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_GetEvaluationDataset_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_get_evaluation_dataset(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.GetEvaluationDatasetRequest( + name="name_value", + ) + + # Make the request + response = client.get_evaluation_dataset(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_EvaluationService_GetEvaluationDataset_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_get_evaluation_expectation_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_get_evaluation_expectation_async.py new file mode 100644 index 000000000000..1a3682e03faf --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_get_evaluation_expectation_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEvaluationExpectation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_GetEvaluationExpectation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_get_evaluation_expectation(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.GetEvaluationExpectationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_evaluation_expectation(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_EvaluationService_GetEvaluationExpectation_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_get_evaluation_expectation_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_get_evaluation_expectation_sync.py new file mode 100644 index 000000000000..34f8e262da10 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_get_evaluation_expectation_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEvaluationExpectation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_GetEvaluationExpectation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_get_evaluation_expectation(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.GetEvaluationExpectationRequest( + name="name_value", + ) + + # Make the request + response = client.get_evaluation_expectation(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_EvaluationService_GetEvaluationExpectation_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_get_evaluation_result_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_get_evaluation_result_async.py new file mode 100644 index 000000000000..4c51b7b80cee --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_get_evaluation_result_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEvaluationResult +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_GetEvaluationResult_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_get_evaluation_result(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.GetEvaluationResultRequest( + name="name_value", + ) + + # Make the request + response = await client.get_evaluation_result(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_EvaluationService_GetEvaluationResult_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_get_evaluation_result_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_get_evaluation_result_sync.py new file mode 100644 index 000000000000..807589a381b2 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_get_evaluation_result_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEvaluationResult +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_GetEvaluationResult_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_get_evaluation_result(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.GetEvaluationResultRequest( + name="name_value", + ) + + # Make the request + response = client.get_evaluation_result(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_EvaluationService_GetEvaluationResult_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_get_evaluation_run_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_get_evaluation_run_async.py new file mode 100644 index 000000000000..3f3c514ec1e1 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_get_evaluation_run_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEvaluationRun +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_GetEvaluationRun_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_get_evaluation_run(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.GetEvaluationRunRequest( + name="name_value", + ) + + # Make the request + response = await client.get_evaluation_run(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_EvaluationService_GetEvaluationRun_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_get_evaluation_run_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_get_evaluation_run_sync.py new file mode 100644 index 000000000000..17ec62811429 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_get_evaluation_run_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEvaluationRun +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_GetEvaluationRun_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_get_evaluation_run(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.GetEvaluationRunRequest( + name="name_value", + ) + + # Make the request + response = client.get_evaluation_run(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_EvaluationService_GetEvaluationRun_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_get_evaluation_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_get_evaluation_sync.py new file mode 100644 index 000000000000..4c91676684a9 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_get_evaluation_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEvaluation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_GetEvaluation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_get_evaluation(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.GetEvaluationRequest( + name="name_value", + ) + + # Make the request + response = client.get_evaluation(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_EvaluationService_GetEvaluation_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_get_scheduled_evaluation_run_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_get_scheduled_evaluation_run_async.py new file mode 100644 index 000000000000..0d22c72bdcaa --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_get_scheduled_evaluation_run_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetScheduledEvaluationRun +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_GetScheduledEvaluationRun_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_get_scheduled_evaluation_run(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.GetScheduledEvaluationRunRequest( + name="name_value", + ) + + # Make the request + response = await client.get_scheduled_evaluation_run(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_EvaluationService_GetScheduledEvaluationRun_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_get_scheduled_evaluation_run_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_get_scheduled_evaluation_run_sync.py new file mode 100644 index 000000000000..6434f9dc1308 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_get_scheduled_evaluation_run_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetScheduledEvaluationRun +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_GetScheduledEvaluationRun_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_get_scheduled_evaluation_run(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.GetScheduledEvaluationRunRequest( + name="name_value", + ) + + # Make the request + response = client.get_scheduled_evaluation_run(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_EvaluationService_GetScheduledEvaluationRun_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_import_evaluations_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_import_evaluations_async.py new file mode 100644 index 000000000000..bd0f92f1ed60 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_import_evaluations_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportEvaluations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_ImportEvaluations_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_import_evaluations(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ImportEvaluationsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.import_evaluations(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_EvaluationService_ImportEvaluations_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_import_evaluations_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_import_evaluations_sync.py new file mode 100644 index 000000000000..9199f5569a12 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_import_evaluations_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportEvaluations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_ImportEvaluations_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_import_evaluations(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ImportEvaluationsRequest( + parent="parent_value", + ) + + # Make the request + operation = client.import_evaluations(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_EvaluationService_ImportEvaluations_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_list_evaluation_datasets_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_list_evaluation_datasets_async.py new file mode 100644 index 000000000000..3e6401906f35 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_list_evaluation_datasets_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListEvaluationDatasets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_ListEvaluationDatasets_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_list_evaluation_datasets(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ListEvaluationDatasetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_evaluation_datasets(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END ces_v1beta_generated_EvaluationService_ListEvaluationDatasets_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_list_evaluation_datasets_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_list_evaluation_datasets_sync.py new file mode 100644 index 000000000000..6bb9d14e086d --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_list_evaluation_datasets_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListEvaluationDatasets +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_ListEvaluationDatasets_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_list_evaluation_datasets(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ListEvaluationDatasetsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_evaluation_datasets(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END ces_v1beta_generated_EvaluationService_ListEvaluationDatasets_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_list_evaluation_expectations_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_list_evaluation_expectations_async.py new file mode 100644 index 000000000000..9bd8ffaef1d2 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_list_evaluation_expectations_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListEvaluationExpectations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_ListEvaluationExpectations_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_list_evaluation_expectations(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ListEvaluationExpectationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_evaluation_expectations(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END ces_v1beta_generated_EvaluationService_ListEvaluationExpectations_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_list_evaluation_expectations_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_list_evaluation_expectations_sync.py new file mode 100644 index 000000000000..1bee4642266a --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_list_evaluation_expectations_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListEvaluationExpectations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_ListEvaluationExpectations_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_list_evaluation_expectations(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ListEvaluationExpectationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_evaluation_expectations(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END ces_v1beta_generated_EvaluationService_ListEvaluationExpectations_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_list_evaluation_results_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_list_evaluation_results_async.py new file mode 100644 index 000000000000..26560d862358 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_list_evaluation_results_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListEvaluationResults +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_ListEvaluationResults_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_list_evaluation_results(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ListEvaluationResultsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_evaluation_results(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END ces_v1beta_generated_EvaluationService_ListEvaluationResults_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_list_evaluation_results_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_list_evaluation_results_sync.py new file mode 100644 index 000000000000..44df49f8075f --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_list_evaluation_results_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListEvaluationResults +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_ListEvaluationResults_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_list_evaluation_results(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ListEvaluationResultsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_evaluation_results(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END ces_v1beta_generated_EvaluationService_ListEvaluationResults_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_list_evaluation_runs_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_list_evaluation_runs_async.py new file mode 100644 index 000000000000..d49882301f09 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_list_evaluation_runs_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListEvaluationRuns +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_ListEvaluationRuns_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_list_evaluation_runs(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ListEvaluationRunsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_evaluation_runs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END ces_v1beta_generated_EvaluationService_ListEvaluationRuns_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_list_evaluation_runs_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_list_evaluation_runs_sync.py new file mode 100644 index 000000000000..915a18c73d33 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_list_evaluation_runs_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListEvaluationRuns +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_ListEvaluationRuns_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_list_evaluation_runs(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ListEvaluationRunsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_evaluation_runs(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END ces_v1beta_generated_EvaluationService_ListEvaluationRuns_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_list_evaluations_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_list_evaluations_async.py new file mode 100644 index 000000000000..b8e03f654dc4 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_list_evaluations_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListEvaluations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_ListEvaluations_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_list_evaluations(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ListEvaluationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_evaluations(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END ces_v1beta_generated_EvaluationService_ListEvaluations_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_list_evaluations_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_list_evaluations_sync.py new file mode 100644 index 000000000000..f5a6834a6895 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_list_evaluations_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListEvaluations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_ListEvaluations_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_list_evaluations(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ListEvaluationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_evaluations(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END ces_v1beta_generated_EvaluationService_ListEvaluations_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_list_scheduled_evaluation_runs_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_list_scheduled_evaluation_runs_async.py new file mode 100644 index 000000000000..86c0a0ebccce --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_list_scheduled_evaluation_runs_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListScheduledEvaluationRuns +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_ListScheduledEvaluationRuns_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_list_scheduled_evaluation_runs(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ListScheduledEvaluationRunsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_scheduled_evaluation_runs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END ces_v1beta_generated_EvaluationService_ListScheduledEvaluationRuns_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_list_scheduled_evaluation_runs_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_list_scheduled_evaluation_runs_sync.py new file mode 100644 index 000000000000..5c939c1358c5 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_list_scheduled_evaluation_runs_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListScheduledEvaluationRuns +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_ListScheduledEvaluationRuns_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_list_scheduled_evaluation_runs(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ListScheduledEvaluationRunsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_scheduled_evaluation_runs(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END ces_v1beta_generated_EvaluationService_ListScheduledEvaluationRuns_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_run_evaluation_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_run_evaluation_async.py new file mode 100644 index 000000000000..3957b54aa1ea --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_run_evaluation_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RunEvaluation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_RunEvaluation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_run_evaluation(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.RunEvaluationRequest( + app="app_value", + ) + + # Make the request + operation = client.run_evaluation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_EvaluationService_RunEvaluation_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_run_evaluation_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_run_evaluation_sync.py new file mode 100644 index 000000000000..bdfdb505c148 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_run_evaluation_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RunEvaluation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_RunEvaluation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_run_evaluation(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.RunEvaluationRequest( + app="app_value", + ) + + # Make the request + operation = client.run_evaluation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_EvaluationService_RunEvaluation_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_test_persona_voice_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_test_persona_voice_async.py new file mode 100644 index 000000000000..0e3e9386bb7d --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_test_persona_voice_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for TestPersonaVoice +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_TestPersonaVoice_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_test_persona_voice(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.TestPersonaVoiceRequest( + app="app_value", + persona_id="persona_id_value", + text="text_value", + ) + + # Make the request + response = await client.test_persona_voice(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_EvaluationService_TestPersonaVoice_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_test_persona_voice_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_test_persona_voice_sync.py new file mode 100644 index 000000000000..2b221656eb42 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_test_persona_voice_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for TestPersonaVoice +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_TestPersonaVoice_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_test_persona_voice(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.TestPersonaVoiceRequest( + app="app_value", + persona_id="persona_id_value", + text="text_value", + ) + + # Make the request + response = client.test_persona_voice(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_EvaluationService_TestPersonaVoice_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_update_evaluation_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_update_evaluation_async.py new file mode 100644 index 000000000000..44bf8047c8bf --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_update_evaluation_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateEvaluation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_UpdateEvaluation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_update_evaluation(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + evaluation = ces_v1beta.Evaluation() + evaluation.golden.turns.steps.user_input.text = "text_value" + evaluation.display_name = "display_name_value" + + request = ces_v1beta.UpdateEvaluationRequest( + evaluation=evaluation, + ) + + # Make the request + response = await client.update_evaluation(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_EvaluationService_UpdateEvaluation_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_update_evaluation_dataset_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_update_evaluation_dataset_async.py new file mode 100644 index 000000000000..ed118bbc0f8f --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_update_evaluation_dataset_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateEvaluationDataset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_UpdateEvaluationDataset_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_update_evaluation_dataset(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + evaluation_dataset = ces_v1beta.EvaluationDataset() + evaluation_dataset.display_name = "display_name_value" + + request = ces_v1beta.UpdateEvaluationDatasetRequest( + evaluation_dataset=evaluation_dataset, + ) + + # Make the request + response = await client.update_evaluation_dataset(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_EvaluationService_UpdateEvaluationDataset_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_update_evaluation_dataset_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_update_evaluation_dataset_sync.py new file mode 100644 index 000000000000..da6ec2e65f91 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_update_evaluation_dataset_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateEvaluationDataset +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_UpdateEvaluationDataset_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_update_evaluation_dataset(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + evaluation_dataset = ces_v1beta.EvaluationDataset() + evaluation_dataset.display_name = "display_name_value" + + request = ces_v1beta.UpdateEvaluationDatasetRequest( + evaluation_dataset=evaluation_dataset, + ) + + # Make the request + response = client.update_evaluation_dataset(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_EvaluationService_UpdateEvaluationDataset_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_update_evaluation_expectation_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_update_evaluation_expectation_async.py new file mode 100644 index 000000000000..c7eafd8211b3 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_update_evaluation_expectation_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateEvaluationExpectation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_UpdateEvaluationExpectation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_update_evaluation_expectation(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + evaluation_expectation = ces_v1beta.EvaluationExpectation() + evaluation_expectation.llm_criteria.prompt = "prompt_value" + evaluation_expectation.display_name = "display_name_value" + + request = ces_v1beta.UpdateEvaluationExpectationRequest( + evaluation_expectation=evaluation_expectation, + ) + + # Make the request + response = await client.update_evaluation_expectation(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_EvaluationService_UpdateEvaluationExpectation_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_update_evaluation_expectation_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_update_evaluation_expectation_sync.py new file mode 100644 index 000000000000..411c04121ec9 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_update_evaluation_expectation_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateEvaluationExpectation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_UpdateEvaluationExpectation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_update_evaluation_expectation(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + evaluation_expectation = ces_v1beta.EvaluationExpectation() + evaluation_expectation.llm_criteria.prompt = "prompt_value" + evaluation_expectation.display_name = "display_name_value" + + request = ces_v1beta.UpdateEvaluationExpectationRequest( + evaluation_expectation=evaluation_expectation, + ) + + # Make the request + response = client.update_evaluation_expectation(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_EvaluationService_UpdateEvaluationExpectation_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_update_evaluation_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_update_evaluation_sync.py new file mode 100644 index 000000000000..2a0b7da9a083 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_update_evaluation_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateEvaluation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_UpdateEvaluation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_update_evaluation(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + evaluation = ces_v1beta.Evaluation() + evaluation.golden.turns.steps.user_input.text = "text_value" + evaluation.display_name = "display_name_value" + + request = ces_v1beta.UpdateEvaluationRequest( + evaluation=evaluation, + ) + + # Make the request + response = client.update_evaluation(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_EvaluationService_UpdateEvaluation_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_update_scheduled_evaluation_run_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_update_scheduled_evaluation_run_async.py new file mode 100644 index 000000000000..cbfe4294cfec --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_update_scheduled_evaluation_run_async.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateScheduledEvaluationRun +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_UpdateScheduledEvaluationRun_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_update_scheduled_evaluation_run(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + scheduled_evaluation_run = ces_v1beta.ScheduledEvaluationRun() + scheduled_evaluation_run.display_name = "display_name_value" + scheduled_evaluation_run.request.app = "app_value" + scheduled_evaluation_run.scheduling_config.frequency = "BIWEEKLY" + + request = ces_v1beta.UpdateScheduledEvaluationRunRequest( + scheduled_evaluation_run=scheduled_evaluation_run, + ) + + # Make the request + response = await client.update_scheduled_evaluation_run(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_EvaluationService_UpdateScheduledEvaluationRun_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_update_scheduled_evaluation_run_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_update_scheduled_evaluation_run_sync.py new file mode 100644 index 000000000000..0f3d43b27401 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_update_scheduled_evaluation_run_sync.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateScheduledEvaluationRun +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_UpdateScheduledEvaluationRun_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_update_scheduled_evaluation_run(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + scheduled_evaluation_run = ces_v1beta.ScheduledEvaluationRun() + scheduled_evaluation_run.display_name = "display_name_value" + scheduled_evaluation_run.request.app = "app_value" + scheduled_evaluation_run.scheduling_config.frequency = "BIWEEKLY" + + request = ces_v1beta.UpdateScheduledEvaluationRunRequest( + scheduled_evaluation_run=scheduled_evaluation_run, + ) + + # Make the request + response = client.update_scheduled_evaluation_run(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_EvaluationService_UpdateScheduledEvaluationRun_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_upload_evaluation_audio_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_upload_evaluation_audio_async.py new file mode 100644 index 000000000000..d9e3baa7aa85 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_upload_evaluation_audio_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UploadEvaluationAudio +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_UploadEvaluationAudio_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_upload_evaluation_audio(): + # Create a client + client = ces_v1beta.EvaluationServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.UploadEvaluationAudioRequest( + app="app_value", + audio_content=b"audio_content_blob", + ) + + # Make the request + response = await client.upload_evaluation_audio(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_EvaluationService_UploadEvaluationAudio_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_upload_evaluation_audio_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_upload_evaluation_audio_sync.py new file mode 100644 index 000000000000..db751da35349 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_evaluation_service_upload_evaluation_audio_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UploadEvaluationAudio +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_EvaluationService_UploadEvaluationAudio_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_upload_evaluation_audio(): + # Create a client + client = ces_v1beta.EvaluationServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.UploadEvaluationAudioRequest( + app="app_value", + audio_content=b"audio_content_blob", + ) + + # Make the request + response = client.upload_evaluation_audio(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_EvaluationService_UploadEvaluationAudio_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_session_service_bidi_run_session_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_session_service_bidi_run_session_async.py new file mode 100644 index 000000000000..326955bc4bc4 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_session_service_bidi_run_session_async.py @@ -0,0 +1,67 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BidiRunSession +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_SessionService_BidiRunSession_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_bidi_run_session(): + # Create a client + client = ces_v1beta.SessionServiceAsyncClient() + + # Initialize request argument(s) + config = ces_v1beta.SessionConfig() + config.session = "session_value" + + request = ces_v1beta.BidiSessionClientMessage( + config=config, + ) + + # This method expects an iterator which contains + # 'ces_v1beta.BidiSessionClientMessage' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = await client.bidi_run_session(requests=request_generator()) + + # Handle the response + async for response in stream: + print(response) + + +# [END ces_v1beta_generated_SessionService_BidiRunSession_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_session_service_bidi_run_session_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_session_service_bidi_run_session_sync.py new file mode 100644 index 000000000000..d704aee33509 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_session_service_bidi_run_session_sync.py @@ -0,0 +1,67 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BidiRunSession +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_SessionService_BidiRunSession_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_bidi_run_session(): + # Create a client + client = ces_v1beta.SessionServiceClient() + + # Initialize request argument(s) + config = ces_v1beta.SessionConfig() + config.session = "session_value" + + request = ces_v1beta.BidiSessionClientMessage( + config=config, + ) + + # This method expects an iterator which contains + # 'ces_v1beta.BidiSessionClientMessage' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = client.bidi_run_session(requests=request_generator()) + + # Handle the response + for response in stream: + print(response) + + +# [END ces_v1beta_generated_SessionService_BidiRunSession_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_session_service_run_session_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_session_service_run_session_async.py new file mode 100644 index 000000000000..c4032ec84889 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_session_service_run_session_async.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RunSession +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_SessionService_RunSession_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_run_session(): + # Create a client + client = ces_v1beta.SessionServiceAsyncClient() + + # Initialize request argument(s) + config = ces_v1beta.SessionConfig() + config.session = "session_value" + + inputs = ces_v1beta.SessionInput() + inputs.text = "text_value" + + request = ces_v1beta.RunSessionRequest( + config=config, + inputs=inputs, + ) + + # Make the request + response = await client.run_session(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_SessionService_RunSession_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_session_service_run_session_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_session_service_run_session_sync.py new file mode 100644 index 000000000000..d132033d474c --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_session_service_run_session_sync.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RunSession +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_SessionService_RunSession_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_run_session(): + # Create a client + client = ces_v1beta.SessionServiceClient() + + # Initialize request argument(s) + config = ces_v1beta.SessionConfig() + config.session = "session_value" + + inputs = ces_v1beta.SessionInput() + inputs.text = "text_value" + + request = ces_v1beta.RunSessionRequest( + config=config, + inputs=inputs, + ) + + # Make the request + response = client.run_session(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_SessionService_RunSession_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_tool_service_execute_tool_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_tool_service_execute_tool_async.py new file mode 100644 index 000000000000..6eaa0649f147 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_tool_service_execute_tool_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ExecuteTool +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_ToolService_ExecuteTool_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_execute_tool(): + # Create a client + client = ces_v1beta.ToolServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.ExecuteToolRequest( + tool="tool_value", + parent="parent_value", + ) + + # Make the request + response = await client.execute_tool(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_ToolService_ExecuteTool_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_tool_service_execute_tool_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_tool_service_execute_tool_sync.py new file mode 100644 index 000000000000..cac3c08b4880 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_tool_service_execute_tool_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ExecuteTool +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_ToolService_ExecuteTool_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_execute_tool(): + # Create a client + client = ces_v1beta.ToolServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.ExecuteToolRequest( + tool="tool_value", + parent="parent_value", + ) + + # Make the request + response = client.execute_tool(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_ToolService_ExecuteTool_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_tool_service_retrieve_tool_schema_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_tool_service_retrieve_tool_schema_async.py new file mode 100644 index 000000000000..0d8686f0643b --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_tool_service_retrieve_tool_schema_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RetrieveToolSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_ToolService_RetrieveToolSchema_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_retrieve_tool_schema(): + # Create a client + client = ces_v1beta.ToolServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.RetrieveToolSchemaRequest( + tool="tool_value", + parent="parent_value", + ) + + # Make the request + response = await client.retrieve_tool_schema(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_ToolService_RetrieveToolSchema_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_tool_service_retrieve_tool_schema_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_tool_service_retrieve_tool_schema_sync.py new file mode 100644 index 000000000000..0ea8fc0f1a6c --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_tool_service_retrieve_tool_schema_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RetrieveToolSchema +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_ToolService_RetrieveToolSchema_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_retrieve_tool_schema(): + # Create a client + client = ces_v1beta.ToolServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.RetrieveToolSchemaRequest( + tool="tool_value", + parent="parent_value", + ) + + # Make the request + response = client.retrieve_tool_schema(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_ToolService_RetrieveToolSchema_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_tool_service_retrieve_tools_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_tool_service_retrieve_tools_async.py new file mode 100644 index 000000000000..fd3d106b22b7 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_tool_service_retrieve_tools_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RetrieveTools +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_ToolService_RetrieveTools_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_retrieve_tools(): + # Create a client + client = ces_v1beta.ToolServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.RetrieveToolsRequest( + toolset="toolset_value", + ) + + # Make the request + response = await client.retrieve_tools(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_ToolService_RetrieveTools_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_tool_service_retrieve_tools_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_tool_service_retrieve_tools_sync.py new file mode 100644 index 000000000000..f2ae169fb5fb --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_tool_service_retrieve_tools_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RetrieveTools +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_ToolService_RetrieveTools_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_retrieve_tools(): + # Create a client + client = ces_v1beta.ToolServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.RetrieveToolsRequest( + toolset="toolset_value", + ) + + # Make the request + response = client.retrieve_tools(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_ToolService_RetrieveTools_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_widget_service_generate_chat_token_async.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_widget_service_generate_chat_token_async.py new file mode 100644 index 000000000000..d0b333e4d27a --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_widget_service_generate_chat_token_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateChatToken +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_WidgetService_GenerateChatToken_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +async def sample_generate_chat_token(): + # Create a client + client = ces_v1beta.WidgetServiceAsyncClient() + + # Initialize request argument(s) + request = ces_v1beta.GenerateChatTokenRequest( + name="name_value", + deployment="deployment_value", + ) + + # Make the request + response = await client.generate_chat_token(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_WidgetService_GenerateChatToken_async] diff --git a/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_widget_service_generate_chat_token_sync.py b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_widget_service_generate_chat_token_sync.py new file mode 100644 index 000000000000..a7e8497c785a --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/ces_v1beta_generated_widget_service_generate_chat_token_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateChatToken +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-ces + + +# [START ces_v1beta_generated_WidgetService_GenerateChatToken_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import ces_v1beta + + +def sample_generate_chat_token(): + # Create a client + client = ces_v1beta.WidgetServiceClient() + + # Initialize request argument(s) + request = ces_v1beta.GenerateChatTokenRequest( + name="name_value", + deployment="deployment_value", + ) + + # Make the request + response = client.generate_chat_token(request=request) + + # Handle the response + print(response) + + +# [END ces_v1beta_generated_WidgetService_GenerateChatToken_sync] diff --git a/packages/google-cloud-ces/samples/generated_samples/snippet_metadata_google.cloud.ces.v1beta.json b/packages/google-cloud-ces/samples/generated_samples/snippet_metadata_google.cloud.ces.v1beta.json new file mode 100644 index 000000000000..bae8a0aa0fa9 --- /dev/null +++ b/packages/google-cloud-ces/samples/generated_samples/snippet_metadata_google.cloud.ces.v1beta.json @@ -0,0 +1,13878 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.ces.v1beta", + "version": "v1beta" + } + ], + "language": "PYTHON", + "name": "google-cloud-ces", + "version": "0.0.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.batch_delete_conversations", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.BatchDeleteConversations", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "BatchDeleteConversations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.BatchDeleteConversationsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "batch_delete_conversations" + }, + "description": "Sample for BatchDeleteConversations", + "file": "ces_v1beta_generated_agent_service_batch_delete_conversations_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_BatchDeleteConversations_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_batch_delete_conversations_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.batch_delete_conversations", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.BatchDeleteConversations", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "BatchDeleteConversations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.BatchDeleteConversationsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "batch_delete_conversations" + }, + "description": "Sample for BatchDeleteConversations", + "file": "ces_v1beta_generated_agent_service_batch_delete_conversations_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_BatchDeleteConversations_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_batch_delete_conversations_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.create_agent", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.CreateAgent", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "CreateAgent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.CreateAgentRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "agent", + "type": "google.cloud.ces_v1beta.types.Agent" + }, + { + "name": "agent_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Agent", + "shortName": "create_agent" + }, + "description": "Sample for CreateAgent", + "file": "ces_v1beta_generated_agent_service_create_agent_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_CreateAgent_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_create_agent_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.create_agent", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.CreateAgent", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "CreateAgent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.CreateAgentRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "agent", + "type": "google.cloud.ces_v1beta.types.Agent" + }, + { + "name": "agent_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Agent", + "shortName": "create_agent" + }, + "description": "Sample for CreateAgent", + "file": "ces_v1beta_generated_agent_service_create_agent_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_CreateAgent_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_create_agent_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.create_app_version", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.CreateAppVersion", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "CreateAppVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.CreateAppVersionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "app_version", + "type": "google.cloud.ces_v1beta.types.AppVersion" + }, + { + "name": "app_version_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.AppVersion", + "shortName": "create_app_version" + }, + "description": "Sample for CreateAppVersion", + "file": "ces_v1beta_generated_agent_service_create_app_version_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_CreateAppVersion_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_create_app_version_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.create_app_version", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.CreateAppVersion", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "CreateAppVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.CreateAppVersionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "app_version", + "type": "google.cloud.ces_v1beta.types.AppVersion" + }, + { + "name": "app_version_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.AppVersion", + "shortName": "create_app_version" + }, + "description": "Sample for CreateAppVersion", + "file": "ces_v1beta_generated_agent_service_create_app_version_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_CreateAppVersion_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_create_app_version_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.create_app", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.CreateApp", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "CreateApp" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.CreateAppRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "app", + "type": "google.cloud.ces_v1beta.types.App" + }, + { + "name": "app_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_app" + }, + "description": "Sample for CreateApp", + "file": "ces_v1beta_generated_agent_service_create_app_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_CreateApp_async", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_create_app_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.create_app", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.CreateApp", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "CreateApp" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.CreateAppRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "app", + "type": "google.cloud.ces_v1beta.types.App" + }, + { + "name": "app_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_app" + }, + "description": "Sample for CreateApp", + "file": "ces_v1beta_generated_agent_service_create_app_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_CreateApp_sync", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_create_app_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.create_deployment", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.CreateDeployment", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "CreateDeployment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.CreateDeploymentRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "deployment", + "type": "google.cloud.ces_v1beta.types.Deployment" + }, + { + "name": "deployment_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Deployment", + "shortName": "create_deployment" + }, + "description": "Sample for CreateDeployment", + "file": "ces_v1beta_generated_agent_service_create_deployment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_CreateDeployment_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_create_deployment_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.create_deployment", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.CreateDeployment", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "CreateDeployment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.CreateDeploymentRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "deployment", + "type": "google.cloud.ces_v1beta.types.Deployment" + }, + { + "name": "deployment_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Deployment", + "shortName": "create_deployment" + }, + "description": "Sample for CreateDeployment", + "file": "ces_v1beta_generated_agent_service_create_deployment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_CreateDeployment_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_create_deployment_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.create_example", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.CreateExample", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "CreateExample" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.CreateExampleRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "example", + "type": "google.cloud.ces_v1beta.types.Example" + }, + { + "name": "example_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Example", + "shortName": "create_example" + }, + "description": "Sample for CreateExample", + "file": "ces_v1beta_generated_agent_service_create_example_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_CreateExample_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_create_example_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.create_example", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.CreateExample", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "CreateExample" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.CreateExampleRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "example", + "type": "google.cloud.ces_v1beta.types.Example" + }, + { + "name": "example_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Example", + "shortName": "create_example" + }, + "description": "Sample for CreateExample", + "file": "ces_v1beta_generated_agent_service_create_example_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_CreateExample_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_create_example_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.create_guardrail", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.CreateGuardrail", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "CreateGuardrail" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.CreateGuardrailRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "guardrail", + "type": "google.cloud.ces_v1beta.types.Guardrail" + }, + { + "name": "guardrail_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Guardrail", + "shortName": "create_guardrail" + }, + "description": "Sample for CreateGuardrail", + "file": "ces_v1beta_generated_agent_service_create_guardrail_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_CreateGuardrail_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_create_guardrail_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.create_guardrail", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.CreateGuardrail", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "CreateGuardrail" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.CreateGuardrailRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "guardrail", + "type": "google.cloud.ces_v1beta.types.Guardrail" + }, + { + "name": "guardrail_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Guardrail", + "shortName": "create_guardrail" + }, + "description": "Sample for CreateGuardrail", + "file": "ces_v1beta_generated_agent_service_create_guardrail_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_CreateGuardrail_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_create_guardrail_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.create_tool", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.CreateTool", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "CreateTool" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.CreateToolRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "tool", + "type": "google.cloud.ces_v1beta.types.Tool" + }, + { + "name": "tool_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Tool", + "shortName": "create_tool" + }, + "description": "Sample for CreateTool", + "file": "ces_v1beta_generated_agent_service_create_tool_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_CreateTool_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_create_tool_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.create_tool", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.CreateTool", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "CreateTool" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.CreateToolRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "tool", + "type": "google.cloud.ces_v1beta.types.Tool" + }, + { + "name": "tool_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Tool", + "shortName": "create_tool" + }, + "description": "Sample for CreateTool", + "file": "ces_v1beta_generated_agent_service_create_tool_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_CreateTool_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_create_tool_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.create_toolset", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.CreateToolset", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "CreateToolset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.CreateToolsetRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "toolset", + "type": "google.cloud.ces_v1beta.types.Toolset" + }, + { + "name": "toolset_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Toolset", + "shortName": "create_toolset" + }, + "description": "Sample for CreateToolset", + "file": "ces_v1beta_generated_agent_service_create_toolset_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_CreateToolset_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_create_toolset_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.create_toolset", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.CreateToolset", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "CreateToolset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.CreateToolsetRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "toolset", + "type": "google.cloud.ces_v1beta.types.Toolset" + }, + { + "name": "toolset_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Toolset", + "shortName": "create_toolset" + }, + "description": "Sample for CreateToolset", + "file": "ces_v1beta_generated_agent_service_create_toolset_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_CreateToolset_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_create_toolset_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.delete_agent", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.DeleteAgent", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "DeleteAgent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.DeleteAgentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_agent" + }, + "description": "Sample for DeleteAgent", + "file": "ces_v1beta_generated_agent_service_delete_agent_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_DeleteAgent_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_delete_agent_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.delete_agent", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.DeleteAgent", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "DeleteAgent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.DeleteAgentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_agent" + }, + "description": "Sample for DeleteAgent", + "file": "ces_v1beta_generated_agent_service_delete_agent_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_DeleteAgent_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_delete_agent_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.delete_app_version", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.DeleteAppVersion", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "DeleteAppVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.DeleteAppVersionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_app_version" + }, + "description": "Sample for DeleteAppVersion", + "file": "ces_v1beta_generated_agent_service_delete_app_version_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_DeleteAppVersion_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_delete_app_version_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.delete_app_version", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.DeleteAppVersion", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "DeleteAppVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.DeleteAppVersionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_app_version" + }, + "description": "Sample for DeleteAppVersion", + "file": "ces_v1beta_generated_agent_service_delete_app_version_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_DeleteAppVersion_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_delete_app_version_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.delete_app", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.DeleteApp", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "DeleteApp" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.DeleteAppRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_app" + }, + "description": "Sample for DeleteApp", + "file": "ces_v1beta_generated_agent_service_delete_app_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_DeleteApp_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_delete_app_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.delete_app", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.DeleteApp", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "DeleteApp" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.DeleteAppRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_app" + }, + "description": "Sample for DeleteApp", + "file": "ces_v1beta_generated_agent_service_delete_app_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_DeleteApp_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_delete_app_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.delete_conversation", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.DeleteConversation", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "DeleteConversation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.DeleteConversationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_conversation" + }, + "description": "Sample for DeleteConversation", + "file": "ces_v1beta_generated_agent_service_delete_conversation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_DeleteConversation_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_delete_conversation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.delete_conversation", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.DeleteConversation", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "DeleteConversation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.DeleteConversationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_conversation" + }, + "description": "Sample for DeleteConversation", + "file": "ces_v1beta_generated_agent_service_delete_conversation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_DeleteConversation_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_delete_conversation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.delete_deployment", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.DeleteDeployment", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "DeleteDeployment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.DeleteDeploymentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_deployment" + }, + "description": "Sample for DeleteDeployment", + "file": "ces_v1beta_generated_agent_service_delete_deployment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_DeleteDeployment_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_delete_deployment_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.delete_deployment", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.DeleteDeployment", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "DeleteDeployment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.DeleteDeploymentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_deployment" + }, + "description": "Sample for DeleteDeployment", + "file": "ces_v1beta_generated_agent_service_delete_deployment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_DeleteDeployment_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_delete_deployment_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.delete_example", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.DeleteExample", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "DeleteExample" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.DeleteExampleRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_example" + }, + "description": "Sample for DeleteExample", + "file": "ces_v1beta_generated_agent_service_delete_example_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_DeleteExample_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_delete_example_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.delete_example", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.DeleteExample", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "DeleteExample" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.DeleteExampleRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_example" + }, + "description": "Sample for DeleteExample", + "file": "ces_v1beta_generated_agent_service_delete_example_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_DeleteExample_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_delete_example_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.delete_guardrail", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.DeleteGuardrail", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "DeleteGuardrail" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.DeleteGuardrailRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_guardrail" + }, + "description": "Sample for DeleteGuardrail", + "file": "ces_v1beta_generated_agent_service_delete_guardrail_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_DeleteGuardrail_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_delete_guardrail_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.delete_guardrail", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.DeleteGuardrail", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "DeleteGuardrail" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.DeleteGuardrailRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_guardrail" + }, + "description": "Sample for DeleteGuardrail", + "file": "ces_v1beta_generated_agent_service_delete_guardrail_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_DeleteGuardrail_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_delete_guardrail_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.delete_tool", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.DeleteTool", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "DeleteTool" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.DeleteToolRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_tool" + }, + "description": "Sample for DeleteTool", + "file": "ces_v1beta_generated_agent_service_delete_tool_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_DeleteTool_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_delete_tool_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.delete_tool", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.DeleteTool", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "DeleteTool" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.DeleteToolRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_tool" + }, + "description": "Sample for DeleteTool", + "file": "ces_v1beta_generated_agent_service_delete_tool_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_DeleteTool_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_delete_tool_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.delete_toolset", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.DeleteToolset", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "DeleteToolset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.DeleteToolsetRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_toolset" + }, + "description": "Sample for DeleteToolset", + "file": "ces_v1beta_generated_agent_service_delete_toolset_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_DeleteToolset_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_delete_toolset_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.delete_toolset", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.DeleteToolset", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "DeleteToolset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.DeleteToolsetRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_toolset" + }, + "description": "Sample for DeleteToolset", + "file": "ces_v1beta_generated_agent_service_delete_toolset_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_DeleteToolset_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_delete_toolset_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.export_app", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.ExportApp", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "ExportApp" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.ExportAppRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "export_app" + }, + "description": "Sample for ExportApp", + "file": "ces_v1beta_generated_agent_service_export_app_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_ExportApp_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_export_app_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.export_app", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.ExportApp", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "ExportApp" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.ExportAppRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "export_app" + }, + "description": "Sample for ExportApp", + "file": "ces_v1beta_generated_agent_service_export_app_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_ExportApp_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_export_app_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.get_agent", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.GetAgent", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "GetAgent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.GetAgentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Agent", + "shortName": "get_agent" + }, + "description": "Sample for GetAgent", + "file": "ces_v1beta_generated_agent_service_get_agent_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_GetAgent_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_get_agent_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.get_agent", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.GetAgent", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "GetAgent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.GetAgentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Agent", + "shortName": "get_agent" + }, + "description": "Sample for GetAgent", + "file": "ces_v1beta_generated_agent_service_get_agent_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_GetAgent_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_get_agent_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.get_app_version", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.GetAppVersion", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "GetAppVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.GetAppVersionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.AppVersion", + "shortName": "get_app_version" + }, + "description": "Sample for GetAppVersion", + "file": "ces_v1beta_generated_agent_service_get_app_version_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_GetAppVersion_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_get_app_version_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.get_app_version", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.GetAppVersion", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "GetAppVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.GetAppVersionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.AppVersion", + "shortName": "get_app_version" + }, + "description": "Sample for GetAppVersion", + "file": "ces_v1beta_generated_agent_service_get_app_version_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_GetAppVersion_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_get_app_version_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.get_app", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.GetApp", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "GetApp" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.GetAppRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.App", + "shortName": "get_app" + }, + "description": "Sample for GetApp", + "file": "ces_v1beta_generated_agent_service_get_app_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_GetApp_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_get_app_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.get_app", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.GetApp", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "GetApp" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.GetAppRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.App", + "shortName": "get_app" + }, + "description": "Sample for GetApp", + "file": "ces_v1beta_generated_agent_service_get_app_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_GetApp_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_get_app_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.get_changelog", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.GetChangelog", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "GetChangelog" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.GetChangelogRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Changelog", + "shortName": "get_changelog" + }, + "description": "Sample for GetChangelog", + "file": "ces_v1beta_generated_agent_service_get_changelog_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_GetChangelog_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_get_changelog_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.get_changelog", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.GetChangelog", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "GetChangelog" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.GetChangelogRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Changelog", + "shortName": "get_changelog" + }, + "description": "Sample for GetChangelog", + "file": "ces_v1beta_generated_agent_service_get_changelog_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_GetChangelog_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_get_changelog_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.get_conversation", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.GetConversation", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "GetConversation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.GetConversationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Conversation", + "shortName": "get_conversation" + }, + "description": "Sample for GetConversation", + "file": "ces_v1beta_generated_agent_service_get_conversation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_GetConversation_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_get_conversation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.get_conversation", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.GetConversation", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "GetConversation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.GetConversationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Conversation", + "shortName": "get_conversation" + }, + "description": "Sample for GetConversation", + "file": "ces_v1beta_generated_agent_service_get_conversation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_GetConversation_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_get_conversation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.get_deployment", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.GetDeployment", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "GetDeployment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.GetDeploymentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Deployment", + "shortName": "get_deployment" + }, + "description": "Sample for GetDeployment", + "file": "ces_v1beta_generated_agent_service_get_deployment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_GetDeployment_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_get_deployment_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.get_deployment", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.GetDeployment", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "GetDeployment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.GetDeploymentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Deployment", + "shortName": "get_deployment" + }, + "description": "Sample for GetDeployment", + "file": "ces_v1beta_generated_agent_service_get_deployment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_GetDeployment_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_get_deployment_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.get_example", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.GetExample", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "GetExample" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.GetExampleRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Example", + "shortName": "get_example" + }, + "description": "Sample for GetExample", + "file": "ces_v1beta_generated_agent_service_get_example_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_GetExample_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_get_example_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.get_example", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.GetExample", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "GetExample" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.GetExampleRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Example", + "shortName": "get_example" + }, + "description": "Sample for GetExample", + "file": "ces_v1beta_generated_agent_service_get_example_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_GetExample_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_get_example_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.get_guardrail", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.GetGuardrail", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "GetGuardrail" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.GetGuardrailRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Guardrail", + "shortName": "get_guardrail" + }, + "description": "Sample for GetGuardrail", + "file": "ces_v1beta_generated_agent_service_get_guardrail_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_GetGuardrail_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_get_guardrail_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.get_guardrail", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.GetGuardrail", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "GetGuardrail" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.GetGuardrailRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Guardrail", + "shortName": "get_guardrail" + }, + "description": "Sample for GetGuardrail", + "file": "ces_v1beta_generated_agent_service_get_guardrail_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_GetGuardrail_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_get_guardrail_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.get_tool", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.GetTool", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "GetTool" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.GetToolRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Tool", + "shortName": "get_tool" + }, + "description": "Sample for GetTool", + "file": "ces_v1beta_generated_agent_service_get_tool_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_GetTool_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_get_tool_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.get_tool", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.GetTool", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "GetTool" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.GetToolRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Tool", + "shortName": "get_tool" + }, + "description": "Sample for GetTool", + "file": "ces_v1beta_generated_agent_service_get_tool_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_GetTool_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_get_tool_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.get_toolset", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.GetToolset", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "GetToolset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.GetToolsetRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Toolset", + "shortName": "get_toolset" + }, + "description": "Sample for GetToolset", + "file": "ces_v1beta_generated_agent_service_get_toolset_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_GetToolset_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_get_toolset_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.get_toolset", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.GetToolset", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "GetToolset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.GetToolsetRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Toolset", + "shortName": "get_toolset" + }, + "description": "Sample for GetToolset", + "file": "ces_v1beta_generated_agent_service_get_toolset_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_GetToolset_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_get_toolset_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.import_app", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.ImportApp", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "ImportApp" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.ImportAppRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "display_name", + "type": "str" + }, + { + "name": "app_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "import_app" + }, + "description": "Sample for ImportApp", + "file": "ces_v1beta_generated_agent_service_import_app_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_ImportApp_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_import_app_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.import_app", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.ImportApp", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "ImportApp" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.ImportAppRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "display_name", + "type": "str" + }, + { + "name": "app_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "import_app" + }, + "description": "Sample for ImportApp", + "file": "ces_v1beta_generated_agent_service_import_app_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_ImportApp_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_import_app_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.list_agents", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.ListAgents", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "ListAgents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.ListAgentsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.services.agent_service.pagers.ListAgentsAsyncPager", + "shortName": "list_agents" + }, + "description": "Sample for ListAgents", + "file": "ces_v1beta_generated_agent_service_list_agents_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_ListAgents_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_list_agents_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.list_agents", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.ListAgents", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "ListAgents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.ListAgentsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.services.agent_service.pagers.ListAgentsPager", + "shortName": "list_agents" + }, + "description": "Sample for ListAgents", + "file": "ces_v1beta_generated_agent_service_list_agents_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_ListAgents_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_list_agents_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.list_app_versions", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.ListAppVersions", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "ListAppVersions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.ListAppVersionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.services.agent_service.pagers.ListAppVersionsAsyncPager", + "shortName": "list_app_versions" + }, + "description": "Sample for ListAppVersions", + "file": "ces_v1beta_generated_agent_service_list_app_versions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_ListAppVersions_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_list_app_versions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.list_app_versions", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.ListAppVersions", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "ListAppVersions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.ListAppVersionsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.services.agent_service.pagers.ListAppVersionsPager", + "shortName": "list_app_versions" + }, + "description": "Sample for ListAppVersions", + "file": "ces_v1beta_generated_agent_service_list_app_versions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_ListAppVersions_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_list_app_versions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.list_apps", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.ListApps", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "ListApps" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.ListAppsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.services.agent_service.pagers.ListAppsAsyncPager", + "shortName": "list_apps" + }, + "description": "Sample for ListApps", + "file": "ces_v1beta_generated_agent_service_list_apps_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_ListApps_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_list_apps_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.list_apps", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.ListApps", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "ListApps" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.ListAppsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.services.agent_service.pagers.ListAppsPager", + "shortName": "list_apps" + }, + "description": "Sample for ListApps", + "file": "ces_v1beta_generated_agent_service_list_apps_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_ListApps_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_list_apps_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.list_changelogs", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.ListChangelogs", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "ListChangelogs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.ListChangelogsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.services.agent_service.pagers.ListChangelogsAsyncPager", + "shortName": "list_changelogs" + }, + "description": "Sample for ListChangelogs", + "file": "ces_v1beta_generated_agent_service_list_changelogs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_ListChangelogs_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_list_changelogs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.list_changelogs", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.ListChangelogs", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "ListChangelogs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.ListChangelogsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.services.agent_service.pagers.ListChangelogsPager", + "shortName": "list_changelogs" + }, + "description": "Sample for ListChangelogs", + "file": "ces_v1beta_generated_agent_service_list_changelogs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_ListChangelogs_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_list_changelogs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.list_conversations", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.ListConversations", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "ListConversations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.ListConversationsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.services.agent_service.pagers.ListConversationsAsyncPager", + "shortName": "list_conversations" + }, + "description": "Sample for ListConversations", + "file": "ces_v1beta_generated_agent_service_list_conversations_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_ListConversations_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_list_conversations_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.list_conversations", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.ListConversations", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "ListConversations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.ListConversationsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.services.agent_service.pagers.ListConversationsPager", + "shortName": "list_conversations" + }, + "description": "Sample for ListConversations", + "file": "ces_v1beta_generated_agent_service_list_conversations_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_ListConversations_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_list_conversations_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.list_deployments", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.ListDeployments", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "ListDeployments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.ListDeploymentsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.services.agent_service.pagers.ListDeploymentsAsyncPager", + "shortName": "list_deployments" + }, + "description": "Sample for ListDeployments", + "file": "ces_v1beta_generated_agent_service_list_deployments_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_ListDeployments_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_list_deployments_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.list_deployments", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.ListDeployments", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "ListDeployments" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.ListDeploymentsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.services.agent_service.pagers.ListDeploymentsPager", + "shortName": "list_deployments" + }, + "description": "Sample for ListDeployments", + "file": "ces_v1beta_generated_agent_service_list_deployments_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_ListDeployments_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_list_deployments_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.list_examples", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.ListExamples", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "ListExamples" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.ListExamplesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.services.agent_service.pagers.ListExamplesAsyncPager", + "shortName": "list_examples" + }, + "description": "Sample for ListExamples", + "file": "ces_v1beta_generated_agent_service_list_examples_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_ListExamples_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_list_examples_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.list_examples", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.ListExamples", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "ListExamples" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.ListExamplesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.services.agent_service.pagers.ListExamplesPager", + "shortName": "list_examples" + }, + "description": "Sample for ListExamples", + "file": "ces_v1beta_generated_agent_service_list_examples_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_ListExamples_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_list_examples_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.list_guardrails", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.ListGuardrails", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "ListGuardrails" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.ListGuardrailsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.services.agent_service.pagers.ListGuardrailsAsyncPager", + "shortName": "list_guardrails" + }, + "description": "Sample for ListGuardrails", + "file": "ces_v1beta_generated_agent_service_list_guardrails_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_ListGuardrails_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_list_guardrails_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.list_guardrails", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.ListGuardrails", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "ListGuardrails" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.ListGuardrailsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.services.agent_service.pagers.ListGuardrailsPager", + "shortName": "list_guardrails" + }, + "description": "Sample for ListGuardrails", + "file": "ces_v1beta_generated_agent_service_list_guardrails_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_ListGuardrails_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_list_guardrails_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.list_tools", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.ListTools", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "ListTools" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.ListToolsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.services.agent_service.pagers.ListToolsAsyncPager", + "shortName": "list_tools" + }, + "description": "Sample for ListTools", + "file": "ces_v1beta_generated_agent_service_list_tools_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_ListTools_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_list_tools_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.list_tools", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.ListTools", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "ListTools" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.ListToolsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.services.agent_service.pagers.ListToolsPager", + "shortName": "list_tools" + }, + "description": "Sample for ListTools", + "file": "ces_v1beta_generated_agent_service_list_tools_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_ListTools_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_list_tools_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.list_toolsets", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.ListToolsets", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "ListToolsets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.ListToolsetsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.services.agent_service.pagers.ListToolsetsAsyncPager", + "shortName": "list_toolsets" + }, + "description": "Sample for ListToolsets", + "file": "ces_v1beta_generated_agent_service_list_toolsets_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_ListToolsets_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_list_toolsets_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.list_toolsets", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.ListToolsets", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "ListToolsets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.ListToolsetsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.services.agent_service.pagers.ListToolsetsPager", + "shortName": "list_toolsets" + }, + "description": "Sample for ListToolsets", + "file": "ces_v1beta_generated_agent_service_list_toolsets_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_ListToolsets_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_list_toolsets_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.restore_app_version", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.RestoreAppVersion", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "RestoreAppVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.RestoreAppVersionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "restore_app_version" + }, + "description": "Sample for RestoreAppVersion", + "file": "ces_v1beta_generated_agent_service_restore_app_version_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_RestoreAppVersion_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_restore_app_version_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.restore_app_version", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.RestoreAppVersion", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "RestoreAppVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.RestoreAppVersionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "restore_app_version" + }, + "description": "Sample for RestoreAppVersion", + "file": "ces_v1beta_generated_agent_service_restore_app_version_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_RestoreAppVersion_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_restore_app_version_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.update_agent", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.UpdateAgent", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "UpdateAgent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.UpdateAgentRequest" + }, + { + "name": "agent", + "type": "google.cloud.ces_v1beta.types.Agent" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Agent", + "shortName": "update_agent" + }, + "description": "Sample for UpdateAgent", + "file": "ces_v1beta_generated_agent_service_update_agent_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_UpdateAgent_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_update_agent_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.update_agent", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.UpdateAgent", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "UpdateAgent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.UpdateAgentRequest" + }, + { + "name": "agent", + "type": "google.cloud.ces_v1beta.types.Agent" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Agent", + "shortName": "update_agent" + }, + "description": "Sample for UpdateAgent", + "file": "ces_v1beta_generated_agent_service_update_agent_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_UpdateAgent_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_update_agent_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.update_app", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.UpdateApp", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "UpdateApp" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.UpdateAppRequest" + }, + { + "name": "app", + "type": "google.cloud.ces_v1beta.types.App" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.App", + "shortName": "update_app" + }, + "description": "Sample for UpdateApp", + "file": "ces_v1beta_generated_agent_service_update_app_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_UpdateApp_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_update_app_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.update_app", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.UpdateApp", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "UpdateApp" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.UpdateAppRequest" + }, + { + "name": "app", + "type": "google.cloud.ces_v1beta.types.App" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.App", + "shortName": "update_app" + }, + "description": "Sample for UpdateApp", + "file": "ces_v1beta_generated_agent_service_update_app_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_UpdateApp_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_update_app_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.update_deployment", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.UpdateDeployment", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "UpdateDeployment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.UpdateDeploymentRequest" + }, + { + "name": "deployment", + "type": "google.cloud.ces_v1beta.types.Deployment" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Deployment", + "shortName": "update_deployment" + }, + "description": "Sample for UpdateDeployment", + "file": "ces_v1beta_generated_agent_service_update_deployment_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_UpdateDeployment_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_update_deployment_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.update_deployment", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.UpdateDeployment", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "UpdateDeployment" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.UpdateDeploymentRequest" + }, + { + "name": "deployment", + "type": "google.cloud.ces_v1beta.types.Deployment" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Deployment", + "shortName": "update_deployment" + }, + "description": "Sample for UpdateDeployment", + "file": "ces_v1beta_generated_agent_service_update_deployment_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_UpdateDeployment_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_update_deployment_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.update_example", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.UpdateExample", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "UpdateExample" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.UpdateExampleRequest" + }, + { + "name": "example", + "type": "google.cloud.ces_v1beta.types.Example" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Example", + "shortName": "update_example" + }, + "description": "Sample for UpdateExample", + "file": "ces_v1beta_generated_agent_service_update_example_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_UpdateExample_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_update_example_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.update_example", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.UpdateExample", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "UpdateExample" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.UpdateExampleRequest" + }, + { + "name": "example", + "type": "google.cloud.ces_v1beta.types.Example" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Example", + "shortName": "update_example" + }, + "description": "Sample for UpdateExample", + "file": "ces_v1beta_generated_agent_service_update_example_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_UpdateExample_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_update_example_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.update_guardrail", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.UpdateGuardrail", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "UpdateGuardrail" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.UpdateGuardrailRequest" + }, + { + "name": "guardrail", + "type": "google.cloud.ces_v1beta.types.Guardrail" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Guardrail", + "shortName": "update_guardrail" + }, + "description": "Sample for UpdateGuardrail", + "file": "ces_v1beta_generated_agent_service_update_guardrail_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_UpdateGuardrail_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_update_guardrail_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.update_guardrail", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.UpdateGuardrail", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "UpdateGuardrail" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.UpdateGuardrailRequest" + }, + { + "name": "guardrail", + "type": "google.cloud.ces_v1beta.types.Guardrail" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Guardrail", + "shortName": "update_guardrail" + }, + "description": "Sample for UpdateGuardrail", + "file": "ces_v1beta_generated_agent_service_update_guardrail_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_UpdateGuardrail_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_update_guardrail_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.update_tool", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.UpdateTool", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "UpdateTool" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.UpdateToolRequest" + }, + { + "name": "tool", + "type": "google.cloud.ces_v1beta.types.Tool" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Tool", + "shortName": "update_tool" + }, + "description": "Sample for UpdateTool", + "file": "ces_v1beta_generated_agent_service_update_tool_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_UpdateTool_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_update_tool_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.update_tool", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.UpdateTool", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "UpdateTool" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.UpdateToolRequest" + }, + { + "name": "tool", + "type": "google.cloud.ces_v1beta.types.Tool" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Tool", + "shortName": "update_tool" + }, + "description": "Sample for UpdateTool", + "file": "ces_v1beta_generated_agent_service_update_tool_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_UpdateTool_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_update_tool_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient", + "shortName": "AgentServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceAsyncClient.update_toolset", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.UpdateToolset", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "UpdateToolset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.UpdateToolsetRequest" + }, + { + "name": "toolset", + "type": "google.cloud.ces_v1beta.types.Toolset" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Toolset", + "shortName": "update_toolset" + }, + "description": "Sample for UpdateToolset", + "file": "ces_v1beta_generated_agent_service_update_toolset_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_UpdateToolset_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_update_toolset_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.AgentServiceClient", + "shortName": "AgentServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.AgentServiceClient.update_toolset", + "method": { + "fullName": "google.cloud.ces.v1beta.AgentService.UpdateToolset", + "service": { + "fullName": "google.cloud.ces.v1beta.AgentService", + "shortName": "AgentService" + }, + "shortName": "UpdateToolset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.UpdateToolsetRequest" + }, + { + "name": "toolset", + "type": "google.cloud.ces_v1beta.types.Toolset" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Toolset", + "shortName": "update_toolset" + }, + "description": "Sample for UpdateToolset", + "file": "ces_v1beta_generated_agent_service_update_toolset_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_AgentService_UpdateToolset_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_agent_service_update_toolset_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.create_evaluation_dataset", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.CreateEvaluationDataset", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "CreateEvaluationDataset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.CreateEvaluationDatasetRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "evaluation_dataset", + "type": "google.cloud.ces_v1beta.types.EvaluationDataset" + }, + { + "name": "evaluation_dataset_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.EvaluationDataset", + "shortName": "create_evaluation_dataset" + }, + "description": "Sample for CreateEvaluationDataset", + "file": "ces_v1beta_generated_evaluation_service_create_evaluation_dataset_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_CreateEvaluationDataset_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_create_evaluation_dataset_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.create_evaluation_dataset", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.CreateEvaluationDataset", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "CreateEvaluationDataset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.CreateEvaluationDatasetRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "evaluation_dataset", + "type": "google.cloud.ces_v1beta.types.EvaluationDataset" + }, + { + "name": "evaluation_dataset_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.EvaluationDataset", + "shortName": "create_evaluation_dataset" + }, + "description": "Sample for CreateEvaluationDataset", + "file": "ces_v1beta_generated_evaluation_service_create_evaluation_dataset_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_CreateEvaluationDataset_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_create_evaluation_dataset_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.create_evaluation_expectation", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.CreateEvaluationExpectation", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "CreateEvaluationExpectation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.CreateEvaluationExpectationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "evaluation_expectation", + "type": "google.cloud.ces_v1beta.types.EvaluationExpectation" + }, + { + "name": "evaluation_expectation_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.EvaluationExpectation", + "shortName": "create_evaluation_expectation" + }, + "description": "Sample for CreateEvaluationExpectation", + "file": "ces_v1beta_generated_evaluation_service_create_evaluation_expectation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_CreateEvaluationExpectation_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_create_evaluation_expectation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.create_evaluation_expectation", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.CreateEvaluationExpectation", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "CreateEvaluationExpectation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.CreateEvaluationExpectationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "evaluation_expectation", + "type": "google.cloud.ces_v1beta.types.EvaluationExpectation" + }, + { + "name": "evaluation_expectation_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.EvaluationExpectation", + "shortName": "create_evaluation_expectation" + }, + "description": "Sample for CreateEvaluationExpectation", + "file": "ces_v1beta_generated_evaluation_service_create_evaluation_expectation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_CreateEvaluationExpectation_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_create_evaluation_expectation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.create_evaluation", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.CreateEvaluation", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "CreateEvaluation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.CreateEvaluationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "evaluation", + "type": "google.cloud.ces_v1beta.types.Evaluation" + }, + { + "name": "evaluation_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Evaluation", + "shortName": "create_evaluation" + }, + "description": "Sample for CreateEvaluation", + "file": "ces_v1beta_generated_evaluation_service_create_evaluation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_CreateEvaluation_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_create_evaluation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.create_evaluation", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.CreateEvaluation", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "CreateEvaluation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.CreateEvaluationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "evaluation", + "type": "google.cloud.ces_v1beta.types.Evaluation" + }, + { + "name": "evaluation_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Evaluation", + "shortName": "create_evaluation" + }, + "description": "Sample for CreateEvaluation", + "file": "ces_v1beta_generated_evaluation_service_create_evaluation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_CreateEvaluation_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_create_evaluation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.create_scheduled_evaluation_run", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.CreateScheduledEvaluationRun", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "CreateScheduledEvaluationRun" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.CreateScheduledEvaluationRunRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "scheduled_evaluation_run", + "type": "google.cloud.ces_v1beta.types.ScheduledEvaluationRun" + }, + { + "name": "scheduled_evaluation_run_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.ScheduledEvaluationRun", + "shortName": "create_scheduled_evaluation_run" + }, + "description": "Sample for CreateScheduledEvaluationRun", + "file": "ces_v1beta_generated_evaluation_service_create_scheduled_evaluation_run_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_CreateScheduledEvaluationRun_async", + "segments": [ + { + "end": 57, + "start": 27, + "type": "FULL" + }, + { + "end": 57, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 54, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 58, + "start": 55, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_create_scheduled_evaluation_run_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.create_scheduled_evaluation_run", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.CreateScheduledEvaluationRun", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "CreateScheduledEvaluationRun" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.CreateScheduledEvaluationRunRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "scheduled_evaluation_run", + "type": "google.cloud.ces_v1beta.types.ScheduledEvaluationRun" + }, + { + "name": "scheduled_evaluation_run_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.ScheduledEvaluationRun", + "shortName": "create_scheduled_evaluation_run" + }, + "description": "Sample for CreateScheduledEvaluationRun", + "file": "ces_v1beta_generated_evaluation_service_create_scheduled_evaluation_run_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_CreateScheduledEvaluationRun_sync", + "segments": [ + { + "end": 57, + "start": 27, + "type": "FULL" + }, + { + "end": 57, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 54, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 58, + "start": 55, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_create_scheduled_evaluation_run_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.delete_evaluation_dataset", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationDataset", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "DeleteEvaluationDataset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.DeleteEvaluationDatasetRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_evaluation_dataset" + }, + "description": "Sample for DeleteEvaluationDataset", + "file": "ces_v1beta_generated_evaluation_service_delete_evaluation_dataset_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_DeleteEvaluationDataset_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_delete_evaluation_dataset_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.delete_evaluation_dataset", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationDataset", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "DeleteEvaluationDataset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.DeleteEvaluationDatasetRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_evaluation_dataset" + }, + "description": "Sample for DeleteEvaluationDataset", + "file": "ces_v1beta_generated_evaluation_service_delete_evaluation_dataset_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_DeleteEvaluationDataset_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_delete_evaluation_dataset_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.delete_evaluation_expectation", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationExpectation", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "DeleteEvaluationExpectation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.DeleteEvaluationExpectationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_evaluation_expectation" + }, + "description": "Sample for DeleteEvaluationExpectation", + "file": "ces_v1beta_generated_evaluation_service_delete_evaluation_expectation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_DeleteEvaluationExpectation_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_delete_evaluation_expectation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.delete_evaluation_expectation", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationExpectation", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "DeleteEvaluationExpectation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.DeleteEvaluationExpectationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_evaluation_expectation" + }, + "description": "Sample for DeleteEvaluationExpectation", + "file": "ces_v1beta_generated_evaluation_service_delete_evaluation_expectation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_DeleteEvaluationExpectation_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_delete_evaluation_expectation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.delete_evaluation_result", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationResult", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "DeleteEvaluationResult" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.DeleteEvaluationResultRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_evaluation_result" + }, + "description": "Sample for DeleteEvaluationResult", + "file": "ces_v1beta_generated_evaluation_service_delete_evaluation_result_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_DeleteEvaluationResult_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_delete_evaluation_result_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.delete_evaluation_result", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationResult", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "DeleteEvaluationResult" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.DeleteEvaluationResultRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_evaluation_result" + }, + "description": "Sample for DeleteEvaluationResult", + "file": "ces_v1beta_generated_evaluation_service_delete_evaluation_result_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_DeleteEvaluationResult_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_delete_evaluation_result_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.delete_evaluation_run", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationRun", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "DeleteEvaluationRun" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.DeleteEvaluationRunRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_evaluation_run" + }, + "description": "Sample for DeleteEvaluationRun", + "file": "ces_v1beta_generated_evaluation_service_delete_evaluation_run_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_DeleteEvaluationRun_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_delete_evaluation_run_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.delete_evaluation_run", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.DeleteEvaluationRun", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "DeleteEvaluationRun" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.DeleteEvaluationRunRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_evaluation_run" + }, + "description": "Sample for DeleteEvaluationRun", + "file": "ces_v1beta_generated_evaluation_service_delete_evaluation_run_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_DeleteEvaluationRun_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_delete_evaluation_run_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.delete_evaluation", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.DeleteEvaluation", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "DeleteEvaluation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.DeleteEvaluationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_evaluation" + }, + "description": "Sample for DeleteEvaluation", + "file": "ces_v1beta_generated_evaluation_service_delete_evaluation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_DeleteEvaluation_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_delete_evaluation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.delete_evaluation", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.DeleteEvaluation", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "DeleteEvaluation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.DeleteEvaluationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_evaluation" + }, + "description": "Sample for DeleteEvaluation", + "file": "ces_v1beta_generated_evaluation_service_delete_evaluation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_DeleteEvaluation_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_delete_evaluation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.delete_scheduled_evaluation_run", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.DeleteScheduledEvaluationRun", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "DeleteScheduledEvaluationRun" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.DeleteScheduledEvaluationRunRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_scheduled_evaluation_run" + }, + "description": "Sample for DeleteScheduledEvaluationRun", + "file": "ces_v1beta_generated_evaluation_service_delete_scheduled_evaluation_run_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_DeleteScheduledEvaluationRun_async", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_delete_scheduled_evaluation_run_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.delete_scheduled_evaluation_run", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.DeleteScheduledEvaluationRun", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "DeleteScheduledEvaluationRun" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.DeleteScheduledEvaluationRunRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "shortName": "delete_scheduled_evaluation_run" + }, + "description": "Sample for DeleteScheduledEvaluationRun", + "file": "ces_v1beta_generated_evaluation_service_delete_scheduled_evaluation_run_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_DeleteScheduledEvaluationRun_sync", + "segments": [ + { + "end": 49, + "start": 27, + "type": "FULL" + }, + { + "end": 49, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_delete_scheduled_evaluation_run_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.generate_evaluation", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.GenerateEvaluation", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "GenerateEvaluation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.GenerateEvaluationRequest" + }, + { + "name": "conversation", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "generate_evaluation" + }, + "description": "Sample for GenerateEvaluation", + "file": "ces_v1beta_generated_evaluation_service_generate_evaluation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_GenerateEvaluation_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_generate_evaluation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.generate_evaluation", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.GenerateEvaluation", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "GenerateEvaluation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.GenerateEvaluationRequest" + }, + { + "name": "conversation", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "generate_evaluation" + }, + "description": "Sample for GenerateEvaluation", + "file": "ces_v1beta_generated_evaluation_service_generate_evaluation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_GenerateEvaluation_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_generate_evaluation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.get_evaluation_dataset", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.GetEvaluationDataset", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "GetEvaluationDataset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.GetEvaluationDatasetRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.EvaluationDataset", + "shortName": "get_evaluation_dataset" + }, + "description": "Sample for GetEvaluationDataset", + "file": "ces_v1beta_generated_evaluation_service_get_evaluation_dataset_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_GetEvaluationDataset_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_get_evaluation_dataset_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.get_evaluation_dataset", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.GetEvaluationDataset", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "GetEvaluationDataset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.GetEvaluationDatasetRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.EvaluationDataset", + "shortName": "get_evaluation_dataset" + }, + "description": "Sample for GetEvaluationDataset", + "file": "ces_v1beta_generated_evaluation_service_get_evaluation_dataset_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_GetEvaluationDataset_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_get_evaluation_dataset_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.get_evaluation_expectation", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.GetEvaluationExpectation", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "GetEvaluationExpectation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.GetEvaluationExpectationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.EvaluationExpectation", + "shortName": "get_evaluation_expectation" + }, + "description": "Sample for GetEvaluationExpectation", + "file": "ces_v1beta_generated_evaluation_service_get_evaluation_expectation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_GetEvaluationExpectation_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_get_evaluation_expectation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.get_evaluation_expectation", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.GetEvaluationExpectation", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "GetEvaluationExpectation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.GetEvaluationExpectationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.EvaluationExpectation", + "shortName": "get_evaluation_expectation" + }, + "description": "Sample for GetEvaluationExpectation", + "file": "ces_v1beta_generated_evaluation_service_get_evaluation_expectation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_GetEvaluationExpectation_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_get_evaluation_expectation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.get_evaluation_result", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.GetEvaluationResult", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "GetEvaluationResult" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.GetEvaluationResultRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.EvaluationResult", + "shortName": "get_evaluation_result" + }, + "description": "Sample for GetEvaluationResult", + "file": "ces_v1beta_generated_evaluation_service_get_evaluation_result_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_GetEvaluationResult_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_get_evaluation_result_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.get_evaluation_result", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.GetEvaluationResult", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "GetEvaluationResult" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.GetEvaluationResultRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.EvaluationResult", + "shortName": "get_evaluation_result" + }, + "description": "Sample for GetEvaluationResult", + "file": "ces_v1beta_generated_evaluation_service_get_evaluation_result_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_GetEvaluationResult_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_get_evaluation_result_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.get_evaluation_run", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.GetEvaluationRun", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "GetEvaluationRun" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.GetEvaluationRunRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.EvaluationRun", + "shortName": "get_evaluation_run" + }, + "description": "Sample for GetEvaluationRun", + "file": "ces_v1beta_generated_evaluation_service_get_evaluation_run_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_GetEvaluationRun_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_get_evaluation_run_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.get_evaluation_run", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.GetEvaluationRun", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "GetEvaluationRun" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.GetEvaluationRunRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.EvaluationRun", + "shortName": "get_evaluation_run" + }, + "description": "Sample for GetEvaluationRun", + "file": "ces_v1beta_generated_evaluation_service_get_evaluation_run_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_GetEvaluationRun_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_get_evaluation_run_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.get_evaluation", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.GetEvaluation", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "GetEvaluation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.GetEvaluationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Evaluation", + "shortName": "get_evaluation" + }, + "description": "Sample for GetEvaluation", + "file": "ces_v1beta_generated_evaluation_service_get_evaluation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_GetEvaluation_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_get_evaluation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.get_evaluation", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.GetEvaluation", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "GetEvaluation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.GetEvaluationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Evaluation", + "shortName": "get_evaluation" + }, + "description": "Sample for GetEvaluation", + "file": "ces_v1beta_generated_evaluation_service_get_evaluation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_GetEvaluation_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_get_evaluation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.get_scheduled_evaluation_run", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.GetScheduledEvaluationRun", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "GetScheduledEvaluationRun" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.GetScheduledEvaluationRunRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.ScheduledEvaluationRun", + "shortName": "get_scheduled_evaluation_run" + }, + "description": "Sample for GetScheduledEvaluationRun", + "file": "ces_v1beta_generated_evaluation_service_get_scheduled_evaluation_run_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_GetScheduledEvaluationRun_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_get_scheduled_evaluation_run_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.get_scheduled_evaluation_run", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.GetScheduledEvaluationRun", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "GetScheduledEvaluationRun" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.GetScheduledEvaluationRunRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.ScheduledEvaluationRun", + "shortName": "get_scheduled_evaluation_run" + }, + "description": "Sample for GetScheduledEvaluationRun", + "file": "ces_v1beta_generated_evaluation_service_get_scheduled_evaluation_run_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_GetScheduledEvaluationRun_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_get_scheduled_evaluation_run_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.import_evaluations", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.ImportEvaluations", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "ImportEvaluations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.ImportEvaluationsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "import_evaluations" + }, + "description": "Sample for ImportEvaluations", + "file": "ces_v1beta_generated_evaluation_service_import_evaluations_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_ImportEvaluations_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_import_evaluations_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.import_evaluations", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.ImportEvaluations", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "ImportEvaluations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.ImportEvaluationsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "import_evaluations" + }, + "description": "Sample for ImportEvaluations", + "file": "ces_v1beta_generated_evaluation_service_import_evaluations_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_ImportEvaluations_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_import_evaluations_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.list_evaluation_datasets", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.ListEvaluationDatasets", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "ListEvaluationDatasets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.ListEvaluationDatasetsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.services.evaluation_service.pagers.ListEvaluationDatasetsAsyncPager", + "shortName": "list_evaluation_datasets" + }, + "description": "Sample for ListEvaluationDatasets", + "file": "ces_v1beta_generated_evaluation_service_list_evaluation_datasets_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_ListEvaluationDatasets_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_list_evaluation_datasets_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.list_evaluation_datasets", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.ListEvaluationDatasets", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "ListEvaluationDatasets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.ListEvaluationDatasetsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.services.evaluation_service.pagers.ListEvaluationDatasetsPager", + "shortName": "list_evaluation_datasets" + }, + "description": "Sample for ListEvaluationDatasets", + "file": "ces_v1beta_generated_evaluation_service_list_evaluation_datasets_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_ListEvaluationDatasets_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_list_evaluation_datasets_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.list_evaluation_expectations", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.ListEvaluationExpectations", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "ListEvaluationExpectations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.ListEvaluationExpectationsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.services.evaluation_service.pagers.ListEvaluationExpectationsAsyncPager", + "shortName": "list_evaluation_expectations" + }, + "description": "Sample for ListEvaluationExpectations", + "file": "ces_v1beta_generated_evaluation_service_list_evaluation_expectations_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_ListEvaluationExpectations_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_list_evaluation_expectations_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.list_evaluation_expectations", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.ListEvaluationExpectations", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "ListEvaluationExpectations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.ListEvaluationExpectationsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.services.evaluation_service.pagers.ListEvaluationExpectationsPager", + "shortName": "list_evaluation_expectations" + }, + "description": "Sample for ListEvaluationExpectations", + "file": "ces_v1beta_generated_evaluation_service_list_evaluation_expectations_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_ListEvaluationExpectations_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_list_evaluation_expectations_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.list_evaluation_results", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.ListEvaluationResults", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "ListEvaluationResults" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.ListEvaluationResultsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.services.evaluation_service.pagers.ListEvaluationResultsAsyncPager", + "shortName": "list_evaluation_results" + }, + "description": "Sample for ListEvaluationResults", + "file": "ces_v1beta_generated_evaluation_service_list_evaluation_results_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_ListEvaluationResults_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_list_evaluation_results_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.list_evaluation_results", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.ListEvaluationResults", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "ListEvaluationResults" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.ListEvaluationResultsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.services.evaluation_service.pagers.ListEvaluationResultsPager", + "shortName": "list_evaluation_results" + }, + "description": "Sample for ListEvaluationResults", + "file": "ces_v1beta_generated_evaluation_service_list_evaluation_results_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_ListEvaluationResults_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_list_evaluation_results_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.list_evaluation_runs", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.ListEvaluationRuns", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "ListEvaluationRuns" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.ListEvaluationRunsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.services.evaluation_service.pagers.ListEvaluationRunsAsyncPager", + "shortName": "list_evaluation_runs" + }, + "description": "Sample for ListEvaluationRuns", + "file": "ces_v1beta_generated_evaluation_service_list_evaluation_runs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_ListEvaluationRuns_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_list_evaluation_runs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.list_evaluation_runs", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.ListEvaluationRuns", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "ListEvaluationRuns" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.ListEvaluationRunsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.services.evaluation_service.pagers.ListEvaluationRunsPager", + "shortName": "list_evaluation_runs" + }, + "description": "Sample for ListEvaluationRuns", + "file": "ces_v1beta_generated_evaluation_service_list_evaluation_runs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_ListEvaluationRuns_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_list_evaluation_runs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.list_evaluations", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.ListEvaluations", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "ListEvaluations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.ListEvaluationsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.services.evaluation_service.pagers.ListEvaluationsAsyncPager", + "shortName": "list_evaluations" + }, + "description": "Sample for ListEvaluations", + "file": "ces_v1beta_generated_evaluation_service_list_evaluations_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_ListEvaluations_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_list_evaluations_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.list_evaluations", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.ListEvaluations", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "ListEvaluations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.ListEvaluationsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.services.evaluation_service.pagers.ListEvaluationsPager", + "shortName": "list_evaluations" + }, + "description": "Sample for ListEvaluations", + "file": "ces_v1beta_generated_evaluation_service_list_evaluations_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_ListEvaluations_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_list_evaluations_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.list_scheduled_evaluation_runs", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.ListScheduledEvaluationRuns", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "ListScheduledEvaluationRuns" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.ListScheduledEvaluationRunsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.services.evaluation_service.pagers.ListScheduledEvaluationRunsAsyncPager", + "shortName": "list_scheduled_evaluation_runs" + }, + "description": "Sample for ListScheduledEvaluationRuns", + "file": "ces_v1beta_generated_evaluation_service_list_scheduled_evaluation_runs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_ListScheduledEvaluationRuns_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_list_scheduled_evaluation_runs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.list_scheduled_evaluation_runs", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.ListScheduledEvaluationRuns", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "ListScheduledEvaluationRuns" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.ListScheduledEvaluationRunsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.services.evaluation_service.pagers.ListScheduledEvaluationRunsPager", + "shortName": "list_scheduled_evaluation_runs" + }, + "description": "Sample for ListScheduledEvaluationRuns", + "file": "ces_v1beta_generated_evaluation_service_list_scheduled_evaluation_runs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_ListScheduledEvaluationRuns_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_list_scheduled_evaluation_runs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.run_evaluation", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.RunEvaluation", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "RunEvaluation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.RunEvaluationRequest" + }, + { + "name": "app", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "run_evaluation" + }, + "description": "Sample for RunEvaluation", + "file": "ces_v1beta_generated_evaluation_service_run_evaluation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_RunEvaluation_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_run_evaluation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.run_evaluation", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.RunEvaluation", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "RunEvaluation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.RunEvaluationRequest" + }, + { + "name": "app", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "run_evaluation" + }, + "description": "Sample for RunEvaluation", + "file": "ces_v1beta_generated_evaluation_service_run_evaluation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_RunEvaluation_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_run_evaluation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.test_persona_voice", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.TestPersonaVoice", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "TestPersonaVoice" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.TestPersonaVoiceRequest" + }, + { + "name": "app", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.TestPersonaVoiceResponse", + "shortName": "test_persona_voice" + }, + "description": "Sample for TestPersonaVoice", + "file": "ces_v1beta_generated_evaluation_service_test_persona_voice_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_TestPersonaVoice_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_test_persona_voice_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.test_persona_voice", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.TestPersonaVoice", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "TestPersonaVoice" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.TestPersonaVoiceRequest" + }, + { + "name": "app", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.TestPersonaVoiceResponse", + "shortName": "test_persona_voice" + }, + "description": "Sample for TestPersonaVoice", + "file": "ces_v1beta_generated_evaluation_service_test_persona_voice_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_TestPersonaVoice_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_test_persona_voice_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.update_evaluation_dataset", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.UpdateEvaluationDataset", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "UpdateEvaluationDataset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.UpdateEvaluationDatasetRequest" + }, + { + "name": "evaluation_dataset", + "type": "google.cloud.ces_v1beta.types.EvaluationDataset" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.EvaluationDataset", + "shortName": "update_evaluation_dataset" + }, + "description": "Sample for UpdateEvaluationDataset", + "file": "ces_v1beta_generated_evaluation_service_update_evaluation_dataset_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_UpdateEvaluationDataset_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_update_evaluation_dataset_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.update_evaluation_dataset", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.UpdateEvaluationDataset", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "UpdateEvaluationDataset" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.UpdateEvaluationDatasetRequest" + }, + { + "name": "evaluation_dataset", + "type": "google.cloud.ces_v1beta.types.EvaluationDataset" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.EvaluationDataset", + "shortName": "update_evaluation_dataset" + }, + "description": "Sample for UpdateEvaluationDataset", + "file": "ces_v1beta_generated_evaluation_service_update_evaluation_dataset_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_UpdateEvaluationDataset_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_update_evaluation_dataset_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.update_evaluation_expectation", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.UpdateEvaluationExpectation", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "UpdateEvaluationExpectation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.UpdateEvaluationExpectationRequest" + }, + { + "name": "evaluation_expectation", + "type": "google.cloud.ces_v1beta.types.EvaluationExpectation" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.EvaluationExpectation", + "shortName": "update_evaluation_expectation" + }, + "description": "Sample for UpdateEvaluationExpectation", + "file": "ces_v1beta_generated_evaluation_service_update_evaluation_expectation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_UpdateEvaluationExpectation_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_update_evaluation_expectation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.update_evaluation_expectation", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.UpdateEvaluationExpectation", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "UpdateEvaluationExpectation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.UpdateEvaluationExpectationRequest" + }, + { + "name": "evaluation_expectation", + "type": "google.cloud.ces_v1beta.types.EvaluationExpectation" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.EvaluationExpectation", + "shortName": "update_evaluation_expectation" + }, + "description": "Sample for UpdateEvaluationExpectation", + "file": "ces_v1beta_generated_evaluation_service_update_evaluation_expectation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_UpdateEvaluationExpectation_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_update_evaluation_expectation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.update_evaluation", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.UpdateEvaluation", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "UpdateEvaluation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.UpdateEvaluationRequest" + }, + { + "name": "evaluation", + "type": "google.cloud.ces_v1beta.types.Evaluation" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Evaluation", + "shortName": "update_evaluation" + }, + "description": "Sample for UpdateEvaluation", + "file": "ces_v1beta_generated_evaluation_service_update_evaluation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_UpdateEvaluation_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_update_evaluation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.update_evaluation", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.UpdateEvaluation", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "UpdateEvaluation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.UpdateEvaluationRequest" + }, + { + "name": "evaluation", + "type": "google.cloud.ces_v1beta.types.Evaluation" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.Evaluation", + "shortName": "update_evaluation" + }, + "description": "Sample for UpdateEvaluation", + "file": "ces_v1beta_generated_evaluation_service_update_evaluation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_UpdateEvaluation_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_update_evaluation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.update_scheduled_evaluation_run", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.UpdateScheduledEvaluationRun", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "UpdateScheduledEvaluationRun" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.UpdateScheduledEvaluationRunRequest" + }, + { + "name": "scheduled_evaluation_run", + "type": "google.cloud.ces_v1beta.types.ScheduledEvaluationRun" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.ScheduledEvaluationRun", + "shortName": "update_scheduled_evaluation_run" + }, + "description": "Sample for UpdateScheduledEvaluationRun", + "file": "ces_v1beta_generated_evaluation_service_update_scheduled_evaluation_run_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_UpdateScheduledEvaluationRun_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_update_scheduled_evaluation_run_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.update_scheduled_evaluation_run", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.UpdateScheduledEvaluationRun", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "UpdateScheduledEvaluationRun" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.UpdateScheduledEvaluationRunRequest" + }, + { + "name": "scheduled_evaluation_run", + "type": "google.cloud.ces_v1beta.types.ScheduledEvaluationRun" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.ScheduledEvaluationRun", + "shortName": "update_scheduled_evaluation_run" + }, + "description": "Sample for UpdateScheduledEvaluationRun", + "file": "ces_v1beta_generated_evaluation_service_update_scheduled_evaluation_run_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_UpdateScheduledEvaluationRun_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_update_scheduled_evaluation_run_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient", + "shortName": "EvaluationServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceAsyncClient.upload_evaluation_audio", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.UploadEvaluationAudio", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "UploadEvaluationAudio" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.UploadEvaluationAudioRequest" + }, + { + "name": "app", + "type": "str" + }, + { + "name": "audio_content", + "type": "bytes" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.UploadEvaluationAudioResponse", + "shortName": "upload_evaluation_audio" + }, + "description": "Sample for UploadEvaluationAudio", + "file": "ces_v1beta_generated_evaluation_service_upload_evaluation_audio_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_UploadEvaluationAudio_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_upload_evaluation_audio_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient", + "shortName": "EvaluationServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.EvaluationServiceClient.upload_evaluation_audio", + "method": { + "fullName": "google.cloud.ces.v1beta.EvaluationService.UploadEvaluationAudio", + "service": { + "fullName": "google.cloud.ces.v1beta.EvaluationService", + "shortName": "EvaluationService" + }, + "shortName": "UploadEvaluationAudio" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.UploadEvaluationAudioRequest" + }, + { + "name": "app", + "type": "str" + }, + { + "name": "audio_content", + "type": "bytes" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.UploadEvaluationAudioResponse", + "shortName": "upload_evaluation_audio" + }, + "description": "Sample for UploadEvaluationAudio", + "file": "ces_v1beta_generated_evaluation_service_upload_evaluation_audio_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_EvaluationService_UploadEvaluationAudio_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_evaluation_service_upload_evaluation_audio_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.SessionServiceAsyncClient", + "shortName": "SessionServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.SessionServiceAsyncClient.bidi_run_session", + "method": { + "fullName": "google.cloud.ces.v1beta.SessionService.BidiRunSession", + "service": { + "fullName": "google.cloud.ces.v1beta.SessionService", + "shortName": "SessionService" + }, + "shortName": "BidiRunSession" + }, + "parameters": [ + { + "name": "requests", + "type": "Iterator[google.cloud.ces_v1beta.types.BidiSessionClientMessage]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "Iterable[google.cloud.ces_v1beta.types.BidiSessionServerMessage]", + "shortName": "bidi_run_session" + }, + "description": "Sample for BidiRunSession", + "file": "ces_v1beta_generated_session_service_bidi_run_session_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_SessionService_BidiRunSession_async", + "segments": [ + { + "end": 65, + "start": 27, + "type": "FULL" + }, + { + "end": 65, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 58, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 61, + "start": 59, + "type": "REQUEST_EXECUTION" + }, + { + "end": 66, + "start": 62, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_session_service_bidi_run_session_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.SessionServiceClient", + "shortName": "SessionServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.SessionServiceClient.bidi_run_session", + "method": { + "fullName": "google.cloud.ces.v1beta.SessionService.BidiRunSession", + "service": { + "fullName": "google.cloud.ces.v1beta.SessionService", + "shortName": "SessionService" + }, + "shortName": "BidiRunSession" + }, + "parameters": [ + { + "name": "requests", + "type": "Iterator[google.cloud.ces_v1beta.types.BidiSessionClientMessage]" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "Iterable[google.cloud.ces_v1beta.types.BidiSessionServerMessage]", + "shortName": "bidi_run_session" + }, + "description": "Sample for BidiRunSession", + "file": "ces_v1beta_generated_session_service_bidi_run_session_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_SessionService_BidiRunSession_sync", + "segments": [ + { + "end": 65, + "start": 27, + "type": "FULL" + }, + { + "end": 65, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 58, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 61, + "start": 59, + "type": "REQUEST_EXECUTION" + }, + { + "end": 66, + "start": 62, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_session_service_bidi_run_session_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.SessionServiceAsyncClient", + "shortName": "SessionServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.SessionServiceAsyncClient.run_session", + "method": { + "fullName": "google.cloud.ces.v1beta.SessionService.RunSession", + "service": { + "fullName": "google.cloud.ces.v1beta.SessionService", + "shortName": "SessionService" + }, + "shortName": "RunSession" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.RunSessionRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.RunSessionResponse", + "shortName": "run_session" + }, + "description": "Sample for RunSession", + "file": "ces_v1beta_generated_session_service_run_session_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_SessionService_RunSession_async", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 52, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 53, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_session_service_run_session_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.SessionServiceClient", + "shortName": "SessionServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.SessionServiceClient.run_session", + "method": { + "fullName": "google.cloud.ces.v1beta.SessionService.RunSession", + "service": { + "fullName": "google.cloud.ces.v1beta.SessionService", + "shortName": "SessionService" + }, + "shortName": "RunSession" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.RunSessionRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.RunSessionResponse", + "shortName": "run_session" + }, + "description": "Sample for RunSession", + "file": "ces_v1beta_generated_session_service_run_session_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_SessionService_RunSession_sync", + "segments": [ + { + "end": 58, + "start": 27, + "type": "FULL" + }, + { + "end": 58, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 52, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 55, + "start": 53, + "type": "REQUEST_EXECUTION" + }, + { + "end": 59, + "start": 56, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_session_service_run_session_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.ToolServiceAsyncClient", + "shortName": "ToolServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.ToolServiceAsyncClient.execute_tool", + "method": { + "fullName": "google.cloud.ces.v1beta.ToolService.ExecuteTool", + "service": { + "fullName": "google.cloud.ces.v1beta.ToolService", + "shortName": "ToolService" + }, + "shortName": "ExecuteTool" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.ExecuteToolRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.ExecuteToolResponse", + "shortName": "execute_tool" + }, + "description": "Sample for ExecuteTool", + "file": "ces_v1beta_generated_tool_service_execute_tool_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_ToolService_ExecuteTool_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_tool_service_execute_tool_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.ToolServiceClient", + "shortName": "ToolServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.ToolServiceClient.execute_tool", + "method": { + "fullName": "google.cloud.ces.v1beta.ToolService.ExecuteTool", + "service": { + "fullName": "google.cloud.ces.v1beta.ToolService", + "shortName": "ToolService" + }, + "shortName": "ExecuteTool" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.ExecuteToolRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.ExecuteToolResponse", + "shortName": "execute_tool" + }, + "description": "Sample for ExecuteTool", + "file": "ces_v1beta_generated_tool_service_execute_tool_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_ToolService_ExecuteTool_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_tool_service_execute_tool_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.ToolServiceAsyncClient", + "shortName": "ToolServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.ToolServiceAsyncClient.retrieve_tool_schema", + "method": { + "fullName": "google.cloud.ces.v1beta.ToolService.RetrieveToolSchema", + "service": { + "fullName": "google.cloud.ces.v1beta.ToolService", + "shortName": "ToolService" + }, + "shortName": "RetrieveToolSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.RetrieveToolSchemaRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.RetrieveToolSchemaResponse", + "shortName": "retrieve_tool_schema" + }, + "description": "Sample for RetrieveToolSchema", + "file": "ces_v1beta_generated_tool_service_retrieve_tool_schema_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_ToolService_RetrieveToolSchema_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_tool_service_retrieve_tool_schema_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.ToolServiceClient", + "shortName": "ToolServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.ToolServiceClient.retrieve_tool_schema", + "method": { + "fullName": "google.cloud.ces.v1beta.ToolService.RetrieveToolSchema", + "service": { + "fullName": "google.cloud.ces.v1beta.ToolService", + "shortName": "ToolService" + }, + "shortName": "RetrieveToolSchema" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.RetrieveToolSchemaRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.RetrieveToolSchemaResponse", + "shortName": "retrieve_tool_schema" + }, + "description": "Sample for RetrieveToolSchema", + "file": "ces_v1beta_generated_tool_service_retrieve_tool_schema_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_ToolService_RetrieveToolSchema_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_tool_service_retrieve_tool_schema_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.ToolServiceAsyncClient", + "shortName": "ToolServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.ToolServiceAsyncClient.retrieve_tools", + "method": { + "fullName": "google.cloud.ces.v1beta.ToolService.RetrieveTools", + "service": { + "fullName": "google.cloud.ces.v1beta.ToolService", + "shortName": "ToolService" + }, + "shortName": "RetrieveTools" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.RetrieveToolsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.RetrieveToolsResponse", + "shortName": "retrieve_tools" + }, + "description": "Sample for RetrieveTools", + "file": "ces_v1beta_generated_tool_service_retrieve_tools_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_ToolService_RetrieveTools_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_tool_service_retrieve_tools_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.ToolServiceClient", + "shortName": "ToolServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.ToolServiceClient.retrieve_tools", + "method": { + "fullName": "google.cloud.ces.v1beta.ToolService.RetrieveTools", + "service": { + "fullName": "google.cloud.ces.v1beta.ToolService", + "shortName": "ToolService" + }, + "shortName": "RetrieveTools" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.RetrieveToolsRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.RetrieveToolsResponse", + "shortName": "retrieve_tools" + }, + "description": "Sample for RetrieveTools", + "file": "ces_v1beta_generated_tool_service_retrieve_tools_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_ToolService_RetrieveTools_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_tool_service_retrieve_tools_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.ces_v1beta.WidgetServiceAsyncClient", + "shortName": "WidgetServiceAsyncClient" + }, + "fullName": "google.cloud.ces_v1beta.WidgetServiceAsyncClient.generate_chat_token", + "method": { + "fullName": "google.cloud.ces.v1beta.WidgetService.GenerateChatToken", + "service": { + "fullName": "google.cloud.ces.v1beta.WidgetService", + "shortName": "WidgetService" + }, + "shortName": "GenerateChatToken" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.GenerateChatTokenRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.GenerateChatTokenResponse", + "shortName": "generate_chat_token" + }, + "description": "Sample for GenerateChatToken", + "file": "ces_v1beta_generated_widget_service_generate_chat_token_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_WidgetService_GenerateChatToken_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_widget_service_generate_chat_token_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.ces_v1beta.WidgetServiceClient", + "shortName": "WidgetServiceClient" + }, + "fullName": "google.cloud.ces_v1beta.WidgetServiceClient.generate_chat_token", + "method": { + "fullName": "google.cloud.ces.v1beta.WidgetService.GenerateChatToken", + "service": { + "fullName": "google.cloud.ces.v1beta.WidgetService", + "shortName": "WidgetService" + }, + "shortName": "GenerateChatToken" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.ces_v1beta.types.GenerateChatTokenRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.ces_v1beta.types.GenerateChatTokenResponse", + "shortName": "generate_chat_token" + }, + "description": "Sample for GenerateChatToken", + "file": "ces_v1beta_generated_widget_service_generate_chat_token_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "ces_v1beta_generated_WidgetService_GenerateChatToken_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "ces_v1beta_generated_widget_service_generate_chat_token_sync.py" + } + ] +} diff --git a/packages/google-cloud-ces/tests/unit/gapic/ces_v1beta/__init__.py b/packages/google-cloud-ces/tests/unit/gapic/ces_v1beta/__init__.py new file mode 100644 index 000000000000..cbf94b283c70 --- /dev/null +++ b/packages/google-cloud-ces/tests/unit/gapic/ces_v1beta/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# 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. +# diff --git a/packages/google-cloud-ces/tests/unit/gapic/ces_v1beta/test_agent_service.py b/packages/google-cloud-ces/tests/unit/gapic/ces_v1beta/test_agent_service.py new file mode 100644 index 000000000000..9187baa7062e --- /dev/null +++ b/packages/google-cloud-ces/tests/unit/gapic/ces_v1beta/test_agent_service.py @@ -0,0 +1,44645 @@ +# -*- coding: utf-8 -*- +# 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. +# +import os + +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import json +import math +from collections.abc import AsyncIterable, Iterable, Mapping, Sequence + +import grpc +import pytest +from google.api_core import api_core_version +from google.protobuf import json_format +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +import google.api_core.operation_async as operation_async # type: ignore +import google.auth +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.struct_pb2 as struct_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.api_core import ( + client_options, + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + operation, + operations_v1, + path_template, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account + +from google.cloud.ces_v1beta.services.agent_service import ( + AgentServiceAsyncClient, + AgentServiceClient, + pagers, + transports, +) +from google.cloud.ces_v1beta.types import ( + agent, + agent_service, + agent_transfers, + app, + app_version, + auth, + bigquery_export, + changelog, + client_function, + common, + connector_tool, + connector_toolset, + conversation, + data_store, + data_store_tool, + deployment, + example, + fakes, + file_search_tool, + golden_run, + google_search_tool, + guardrail, + mcp_tool, + mcp_toolset, + open_api_tool, + open_api_toolset, + python_function, + schema, + system_tool, + tool, + toolset, + toolset_tool, + widget_tool, +) +from google.cloud.ces_v1beta.types import agent as gcc_agent +from google.cloud.ces_v1beta.types import app as gcc_app +from google.cloud.ces_v1beta.types import app_version as gcc_app_version +from google.cloud.ces_v1beta.types import deployment as gcc_deployment +from google.cloud.ces_v1beta.types import example as gcc_example +from google.cloud.ces_v1beta.types import guardrail as gcc_guardrail +from google.cloud.ces_v1beta.types import tool as gcc_tool +from google.cloud.ces_v1beta.types import toolset as gcc_toolset + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert AgentServiceClient._get_default_mtls_endpoint(None) is None + assert ( + AgentServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + ) + assert ( + AgentServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + AgentServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + AgentServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert AgentServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +def test__read_environment_variables(): + assert AgentServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert AgentServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert AgentServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with pytest.raises(ValueError) as excinfo: + AgentServiceClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + else: + assert AgentServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert AgentServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert AgentServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert AgentServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + AgentServiceClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert AgentServiceClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + + +def test_use_client_cert_effective(): + # Test case 1: Test when `should_use_client_cert` returns True. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch( + "google.auth.transport.mtls.should_use_client_cert", return_value=True + ): + assert AgentServiceClient._use_client_cert_effective() is True + + # Test case 2: Test when `should_use_client_cert` returns False. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should NOT be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch( + "google.auth.transport.mtls.should_use_client_cert", return_value=False + ): + assert AgentServiceClient._use_client_cert_effective() is False + + # Test case 3: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "true". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert AgentServiceClient._use_client_cert_effective() is True + + # Test case 4: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"} + ): + assert AgentServiceClient._use_client_cert_effective() is False + + # Test case 5: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "True". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "True"}): + assert AgentServiceClient._use_client_cert_effective() is True + + # Test case 6: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "False". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"} + ): + assert AgentServiceClient._use_client_cert_effective() is False + + # Test case 7: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "TRUE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "TRUE"}): + assert AgentServiceClient._use_client_cert_effective() is True + + # Test case 8: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "FALSE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"} + ): + assert AgentServiceClient._use_client_cert_effective() is False + + # Test case 9: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not set. + # In this case, the method should return False, which is the default value. + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, clear=True): + assert AgentServiceClient._use_client_cert_effective() is False + + # Test case 10: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should raise a ValueError as the environment variable must be either + # "true" or "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} + ): + with pytest.raises(ValueError): + AgentServiceClient._use_client_cert_effective() + + # Test case 11: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should return False as the environment variable is set to an invalid value. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} + ): + assert AgentServiceClient._use_client_cert_effective() is False + + # Test case 12: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is unset. Also, + # the GOOGLE_API_CONFIG environment variable is unset. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": ""}): + with mock.patch.dict(os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": ""}): + assert AgentServiceClient._use_client_cert_effective() is False + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert AgentServiceClient._get_client_cert_source(None, False) is None + assert ( + AgentServiceClient._get_client_cert_source(mock_provided_cert_source, False) + is None + ) + assert ( + AgentServiceClient._get_client_cert_source(mock_provided_cert_source, True) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + AgentServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + AgentServiceClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + AgentServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AgentServiceClient), +) +@mock.patch.object( + AgentServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AgentServiceAsyncClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = AgentServiceClient._DEFAULT_UNIVERSE + default_endpoint = AgentServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = AgentServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + AgentServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + AgentServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == AgentServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + AgentServiceClient._get_api_endpoint(None, None, default_universe, "auto") + == default_endpoint + ) + assert ( + AgentServiceClient._get_api_endpoint(None, None, default_universe, "always") + == AgentServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + AgentServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == AgentServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + AgentServiceClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + AgentServiceClient._get_api_endpoint(None, None, default_universe, "never") + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + AgentServiceClient._get_api_endpoint( + None, mock_client_cert_source, mock_universe, "auto" + ) + assert ( + str(excinfo.value) + == "mTLS is not supported in any universe other than googleapis.com." + ) + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert ( + AgentServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + AgentServiceClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + AgentServiceClient._get_universe_domain(None, None) + == AgentServiceClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + AgentServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize( + "error_code,cred_info_json,show_cred_info", + [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False), + ], +) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = AgentServiceClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + + +@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = AgentServiceClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (AgentServiceClient, "grpc"), + (AgentServiceAsyncClient, "grpc_asyncio"), + (AgentServiceClient, "rest"), + ], +) +def test_agent_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "ces.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://ces.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.AgentServiceGrpcTransport, "grpc"), + (transports.AgentServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AgentServiceRestTransport, "rest"), + ], +) +def test_agent_service_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (AgentServiceClient, "grpc"), + (AgentServiceAsyncClient, "grpc_asyncio"), + (AgentServiceClient, "rest"), + ], +) +def test_agent_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "ces.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://ces.googleapis.com" + ) + + +def test_agent_service_client_get_transport_class(): + transport = AgentServiceClient.get_transport_class() + available_transports = [ + transports.AgentServiceGrpcTransport, + transports.AgentServiceRestTransport, + ] + assert transport in available_transports + + transport = AgentServiceClient.get_transport_class("grpc") + assert transport == transports.AgentServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (AgentServiceClient, transports.AgentServiceGrpcTransport, "grpc"), + ( + AgentServiceAsyncClient, + transports.AgentServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (AgentServiceClient, transports.AgentServiceRestTransport, "rest"), + ], +) +@mock.patch.object( + AgentServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AgentServiceClient), +) +@mock.patch.object( + AgentServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AgentServiceAsyncClient), +) +def test_agent_service_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(AgentServiceClient, "get_transport_class") as gtc: + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(AgentServiceClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (AgentServiceClient, transports.AgentServiceGrpcTransport, "grpc", "true"), + ( + AgentServiceAsyncClient, + transports.AgentServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (AgentServiceClient, transports.AgentServiceGrpcTransport, "grpc", "false"), + ( + AgentServiceAsyncClient, + transports.AgentServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + (AgentServiceClient, transports.AgentServiceRestTransport, "rest", "true"), + (AgentServiceClient, transports.AgentServiceRestTransport, "rest", "false"), + ], +) +@mock.patch.object( + AgentServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AgentServiceClient), +) +@mock.patch.object( + AgentServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AgentServiceAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_agent_service_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [AgentServiceClient, AgentServiceAsyncClient]) +@mock.patch.object( + AgentServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AgentServiceClient) +) +@mock.patch.object( + AgentServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(AgentServiceAsyncClient), +) +def test_agent_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset. + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source() + ) + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + +@pytest.mark.parametrize("client_class", [AgentServiceClient, AgentServiceAsyncClient]) +@mock.patch.object( + AgentServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AgentServiceClient), +) +@mock.patch.object( + AgentServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(AgentServiceAsyncClient), +) +def test_agent_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = AgentServiceClient._DEFAULT_UNIVERSE + default_endpoint = AgentServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = AgentServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (AgentServiceClient, transports.AgentServiceGrpcTransport, "grpc"), + ( + AgentServiceAsyncClient, + transports.AgentServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (AgentServiceClient, transports.AgentServiceRestTransport, "rest"), + ], +) +def test_agent_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + AgentServiceClient, + transports.AgentServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + AgentServiceAsyncClient, + transports.AgentServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + (AgentServiceClient, transports.AgentServiceRestTransport, "rest", None), + ], +) +def test_agent_service_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_agent_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.ces_v1beta.services.agent_service.transports.AgentServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = AgentServiceClient(client_options={"api_endpoint": "squid.clam.whelk"}) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + AgentServiceClient, + transports.AgentServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + AgentServiceAsyncClient, + transports.AgentServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_agent_service_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object(grpc_helpers, "create_channel") as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "ces.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + "https://www.googleapis.com/auth/ces", + "https://www.googleapis.com/auth/cloud-platform", + ), + scopes=None, + default_host="ces.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.ListAppsRequest, + dict, + ], +) +def test_list_apps(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_apps), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = agent_service.ListAppsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_apps(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.ListAppsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAppsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_apps_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.ListAppsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_apps), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_apps(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.ListAppsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + +def test_list_apps_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_apps in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_apps] = mock_rpc + request = {} + client.list_apps(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_apps(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_apps_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_apps + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_apps + ] = mock_rpc + + request = {} + await client.list_apps(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_apps(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_apps_async( + transport: str = "grpc_asyncio", request_type=agent_service.ListAppsRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_apps), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent_service.ListAppsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_apps(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.ListAppsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAppsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.asyncio +async def test_list_apps_async_from_dict(): + await test_list_apps_async(request_type=dict) + + +def test_list_apps_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.ListAppsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_apps), "__call__") as call: + call.return_value = agent_service.ListAppsResponse() + client.list_apps(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_apps_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.ListAppsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_apps), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent_service.ListAppsResponse() + ) + await client.list_apps(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_apps_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_apps), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = agent_service.ListAppsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_apps( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_apps_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_apps( + agent_service.ListAppsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_apps_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_apps), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = agent_service.ListAppsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent_service.ListAppsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_apps( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_apps_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_apps( + agent_service.ListAppsRequest(), + parent="parent_value", + ) + + +def test_list_apps_pager(transport_name: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_apps), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + agent_service.ListAppsResponse( + apps=[ + app.App(), + app.App(), + app.App(), + ], + next_page_token="abc", + ), + agent_service.ListAppsResponse( + apps=[], + next_page_token="def", + ), + agent_service.ListAppsResponse( + apps=[ + app.App(), + ], + next_page_token="ghi", + ), + agent_service.ListAppsResponse( + apps=[ + app.App(), + app.App(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_apps(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, app.App) for i in results) + + +def test_list_apps_pages(transport_name: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_apps), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + agent_service.ListAppsResponse( + apps=[ + app.App(), + app.App(), + app.App(), + ], + next_page_token="abc", + ), + agent_service.ListAppsResponse( + apps=[], + next_page_token="def", + ), + agent_service.ListAppsResponse( + apps=[ + app.App(), + ], + next_page_token="ghi", + ), + agent_service.ListAppsResponse( + apps=[ + app.App(), + app.App(), + ], + ), + RuntimeError, + ) + pages = list(client.list_apps(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_apps_async_pager(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_apps), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + agent_service.ListAppsResponse( + apps=[ + app.App(), + app.App(), + app.App(), + ], + next_page_token="abc", + ), + agent_service.ListAppsResponse( + apps=[], + next_page_token="def", + ), + agent_service.ListAppsResponse( + apps=[ + app.App(), + ], + next_page_token="ghi", + ), + agent_service.ListAppsResponse( + apps=[ + app.App(), + app.App(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_apps( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, app.App) for i in responses) + + +@pytest.mark.asyncio +async def test_list_apps_async_pages(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_apps), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + agent_service.ListAppsResponse( + apps=[ + app.App(), + app.App(), + app.App(), + ], + next_page_token="abc", + ), + agent_service.ListAppsResponse( + apps=[], + next_page_token="def", + ), + agent_service.ListAppsResponse( + apps=[ + app.App(), + ], + next_page_token="ghi", + ), + agent_service.ListAppsResponse( + apps=[ + app.App(), + app.App(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_apps(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.GetAppRequest, + dict, + ], +) +def test_get_app(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_app), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = app.App( + name="name_value", + display_name="display_name_value", + description="description_value", + pinned=True, + root_agent="root_agent_value", + tool_execution_mode=app.App.ToolExecutionMode.PARALLEL, + global_instruction="global_instruction_value", + guardrails=["guardrails_value"], + etag="etag_value", + deployment_count=1737, + locked=True, + ) + response = client.get_app(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.GetAppRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, app.App) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.pinned is True + assert response.root_agent == "root_agent_value" + assert response.tool_execution_mode == app.App.ToolExecutionMode.PARALLEL + assert response.global_instruction == "global_instruction_value" + assert response.guardrails == ["guardrails_value"] + assert response.etag == "etag_value" + assert response.deployment_count == 1737 + assert response.locked is True + + +def test_get_app_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.GetAppRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_app), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_app(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.GetAppRequest( + name="name_value", + ) + + +def test_get_app_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_app in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_app] = mock_rpc + request = {} + client.get_app(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_app(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_app_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_app + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_app + ] = mock_rpc + + request = {} + await client.get_app(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_app(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_app_async( + transport: str = "grpc_asyncio", request_type=agent_service.GetAppRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_app), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + app.App( + name="name_value", + display_name="display_name_value", + description="description_value", + pinned=True, + root_agent="root_agent_value", + tool_execution_mode=app.App.ToolExecutionMode.PARALLEL, + global_instruction="global_instruction_value", + guardrails=["guardrails_value"], + etag="etag_value", + deployment_count=1737, + locked=True, + ) + ) + response = await client.get_app(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.GetAppRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, app.App) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.pinned is True + assert response.root_agent == "root_agent_value" + assert response.tool_execution_mode == app.App.ToolExecutionMode.PARALLEL + assert response.global_instruction == "global_instruction_value" + assert response.guardrails == ["guardrails_value"] + assert response.etag == "etag_value" + assert response.deployment_count == 1737 + assert response.locked is True + + +@pytest.mark.asyncio +async def test_get_app_async_from_dict(): + await test_get_app_async(request_type=dict) + + +def test_get_app_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.GetAppRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_app), "__call__") as call: + call.return_value = app.App() + client.get_app(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_app_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.GetAppRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_app), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(app.App()) + await client.get_app(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_app_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_app), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = app.App() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_app( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_app_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_app( + agent_service.GetAppRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_app_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_app), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = app.App() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(app.App()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_app( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_app_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_app( + agent_service.GetAppRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.CreateAppRequest, + dict, + ], +) +def test_create_app(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_app), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_app(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.CreateAppRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_app_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.CreateAppRequest( + parent="parent_value", + app_id="app_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_app), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_app(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.CreateAppRequest( + parent="parent_value", + app_id="app_id_value", + ) + + +def test_create_app_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_app in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_app] = mock_rpc + request = {} + client.create_app(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_app(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_app_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_app + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_app + ] = mock_rpc + + request = {} + await client.create_app(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_app(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_app_async( + transport: str = "grpc_asyncio", request_type=agent_service.CreateAppRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_app), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.create_app(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.CreateAppRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_app_async_from_dict(): + await test_create_app_async(request_type=dict) + + +def test_create_app_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.CreateAppRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_app), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_app(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_app_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.CreateAppRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_app), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_app(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_app_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_app), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_app( + parent="parent_value", + app=gcc_app.App(name="name_value"), + app_id="app_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].app + mock_val = gcc_app.App(name="name_value") + assert arg == mock_val + arg = args[0].app_id + mock_val = "app_id_value" + assert arg == mock_val + + +def test_create_app_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_app( + agent_service.CreateAppRequest(), + parent="parent_value", + app=gcc_app.App(name="name_value"), + app_id="app_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_app_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_app), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_app( + parent="parent_value", + app=gcc_app.App(name="name_value"), + app_id="app_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].app + mock_val = gcc_app.App(name="name_value") + assert arg == mock_val + arg = args[0].app_id + mock_val = "app_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_app_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_app( + agent_service.CreateAppRequest(), + parent="parent_value", + app=gcc_app.App(name="name_value"), + app_id="app_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.UpdateAppRequest, + dict, + ], +) +def test_update_app(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_app), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_app.App( + name="name_value", + display_name="display_name_value", + description="description_value", + pinned=True, + root_agent="root_agent_value", + tool_execution_mode=gcc_app.App.ToolExecutionMode.PARALLEL, + global_instruction="global_instruction_value", + guardrails=["guardrails_value"], + etag="etag_value", + deployment_count=1737, + locked=True, + ) + response = client.update_app(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.UpdateAppRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_app.App) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.pinned is True + assert response.root_agent == "root_agent_value" + assert response.tool_execution_mode == gcc_app.App.ToolExecutionMode.PARALLEL + assert response.global_instruction == "global_instruction_value" + assert response.guardrails == ["guardrails_value"] + assert response.etag == "etag_value" + assert response.deployment_count == 1737 + assert response.locked is True + + +def test_update_app_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.UpdateAppRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_app), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_app(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.UpdateAppRequest() + + +def test_update_app_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_app in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_app] = mock_rpc + request = {} + client.update_app(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_app(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_app_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_app + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_app + ] = mock_rpc + + request = {} + await client.update_app(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_app(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_app_async( + transport: str = "grpc_asyncio", request_type=agent_service.UpdateAppRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_app), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_app.App( + name="name_value", + display_name="display_name_value", + description="description_value", + pinned=True, + root_agent="root_agent_value", + tool_execution_mode=gcc_app.App.ToolExecutionMode.PARALLEL, + global_instruction="global_instruction_value", + guardrails=["guardrails_value"], + etag="etag_value", + deployment_count=1737, + locked=True, + ) + ) + response = await client.update_app(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.UpdateAppRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_app.App) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.pinned is True + assert response.root_agent == "root_agent_value" + assert response.tool_execution_mode == gcc_app.App.ToolExecutionMode.PARALLEL + assert response.global_instruction == "global_instruction_value" + assert response.guardrails == ["guardrails_value"] + assert response.etag == "etag_value" + assert response.deployment_count == 1737 + assert response.locked is True + + +@pytest.mark.asyncio +async def test_update_app_async_from_dict(): + await test_update_app_async(request_type=dict) + + +def test_update_app_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.UpdateAppRequest() + + request.app.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_app), "__call__") as call: + call.return_value = gcc_app.App() + client.update_app(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "app.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_app_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.UpdateAppRequest() + + request.app.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_app), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcc_app.App()) + await client.update_app(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "app.name=name_value", + ) in kw["metadata"] + + +def test_update_app_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_app), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_app.App() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_app( + app=gcc_app.App(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].app + mock_val = gcc_app.App(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_app_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_app( + agent_service.UpdateAppRequest(), + app=gcc_app.App(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_app_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_app), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_app.App() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcc_app.App()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_app( + app=gcc_app.App(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].app + mock_val = gcc_app.App(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_app_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_app( + agent_service.UpdateAppRequest(), + app=gcc_app.App(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.DeleteAppRequest, + dict, + ], +) +def test_delete_app(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_app), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_app(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.DeleteAppRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_app_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.DeleteAppRequest( + name="name_value", + etag="etag_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_app), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_app(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.DeleteAppRequest( + name="name_value", + etag="etag_value", + ) + + +def test_delete_app_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_app in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_app] = mock_rpc + request = {} + client.delete_app(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_app(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_app_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_app + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_app + ] = mock_rpc + + request = {} + await client.delete_app(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_app(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_app_async( + transport: str = "grpc_asyncio", request_type=agent_service.DeleteAppRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_app), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.delete_app(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.DeleteAppRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_app_async_from_dict(): + await test_delete_app_async(request_type=dict) + + +def test_delete_app_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.DeleteAppRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_app), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_app(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_app_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.DeleteAppRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_app), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.delete_app(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_app_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_app), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_app( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_app_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_app( + agent_service.DeleteAppRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_app_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_app), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_app( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_app_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_app( + agent_service.DeleteAppRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.ExportAppRequest, + dict, + ], +) +def test_export_app(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.export_app), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.export_app(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.ExportAppRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_export_app_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.ExportAppRequest( + name="name_value", + gcs_uri="gcs_uri_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.export_app), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.export_app(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.ExportAppRequest( + name="name_value", + gcs_uri="gcs_uri_value", + ) + + +def test_export_app_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.export_app in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.export_app] = mock_rpc + request = {} + client.export_app(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.export_app(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_export_app_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.export_app + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.export_app + ] = mock_rpc + + request = {} + await client.export_app(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.export_app(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_export_app_async( + transport: str = "grpc_asyncio", request_type=agent_service.ExportAppRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.export_app), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.export_app(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.ExportAppRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_export_app_async_from_dict(): + await test_export_app_async(request_type=dict) + + +def test_export_app_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.ExportAppRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.export_app), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.export_app(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_export_app_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.ExportAppRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.export_app), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.export_app(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_export_app_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.export_app), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.export_app( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_export_app_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.export_app( + agent_service.ExportAppRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_export_app_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.export_app), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.export_app( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_export_app_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.export_app( + agent_service.ExportAppRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.ImportAppRequest, + dict, + ], +) +def test_import_app(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.import_app), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.import_app(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.ImportAppRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_app_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.ImportAppRequest( + gcs_uri="gcs_uri_value", + parent="parent_value", + display_name="display_name_value", + app_id="app_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.import_app), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.import_app(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.ImportAppRequest( + gcs_uri="gcs_uri_value", + parent="parent_value", + display_name="display_name_value", + app_id="app_id_value", + ) + + +def test_import_app_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.import_app in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.import_app] = mock_rpc + request = {} + client.import_app(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.import_app(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_import_app_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.import_app + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.import_app + ] = mock_rpc + + request = {} + await client.import_app(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.import_app(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_import_app_async( + transport: str = "grpc_asyncio", request_type=agent_service.ImportAppRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.import_app), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.import_app(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.ImportAppRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_app_async_from_dict(): + await test_import_app_async(request_type=dict) + + +def test_import_app_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.ImportAppRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.import_app), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.import_app(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_import_app_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.ImportAppRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.import_app), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.import_app(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_import_app_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.import_app), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.import_app( + parent="parent_value", + display_name="display_name_value", + app_id="app_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].display_name + mock_val = "display_name_value" + assert arg == mock_val + arg = args[0].app_id + mock_val = "app_id_value" + assert arg == mock_val + + +def test_import_app_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.import_app( + agent_service.ImportAppRequest(), + parent="parent_value", + display_name="display_name_value", + app_id="app_id_value", + ) + + +@pytest.mark.asyncio +async def test_import_app_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.import_app), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.import_app( + parent="parent_value", + display_name="display_name_value", + app_id="app_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].display_name + mock_val = "display_name_value" + assert arg == mock_val + arg = args[0].app_id + mock_val = "app_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_import_app_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.import_app( + agent_service.ImportAppRequest(), + parent="parent_value", + display_name="display_name_value", + app_id="app_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.ListAgentsRequest, + dict, + ], +) +def test_list_agents(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_agents), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = agent_service.ListAgentsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_agents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.ListAgentsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAgentsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_agents_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.ListAgentsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_agents), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_agents(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.ListAgentsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + +def test_list_agents_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_agents in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_agents] = mock_rpc + request = {} + client.list_agents(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_agents(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_agents_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_agents + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_agents + ] = mock_rpc + + request = {} + await client.list_agents(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_agents(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_agents_async( + transport: str = "grpc_asyncio", request_type=agent_service.ListAgentsRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_agents), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent_service.ListAgentsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_agents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.ListAgentsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAgentsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_agents_async_from_dict(): + await test_list_agents_async(request_type=dict) + + +def test_list_agents_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.ListAgentsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_agents), "__call__") as call: + call.return_value = agent_service.ListAgentsResponse() + client.list_agents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_agents_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.ListAgentsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_agents), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent_service.ListAgentsResponse() + ) + await client.list_agents(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_agents_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_agents), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = agent_service.ListAgentsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_agents( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_agents_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_agents( + agent_service.ListAgentsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_agents_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_agents), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = agent_service.ListAgentsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent_service.ListAgentsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_agents( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_agents_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_agents( + agent_service.ListAgentsRequest(), + parent="parent_value", + ) + + +def test_list_agents_pager(transport_name: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_agents), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + agent_service.ListAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + agent.Agent(), + ], + next_page_token="abc", + ), + agent_service.ListAgentsResponse( + agents=[], + next_page_token="def", + ), + agent_service.ListAgentsResponse( + agents=[ + agent.Agent(), + ], + next_page_token="ghi", + ), + agent_service.ListAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_agents(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, agent.Agent) for i in results) + + +def test_list_agents_pages(transport_name: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_agents), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + agent_service.ListAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + agent.Agent(), + ], + next_page_token="abc", + ), + agent_service.ListAgentsResponse( + agents=[], + next_page_token="def", + ), + agent_service.ListAgentsResponse( + agents=[ + agent.Agent(), + ], + next_page_token="ghi", + ), + agent_service.ListAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + ], + ), + RuntimeError, + ) + pages = list(client.list_agents(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_agents_async_pager(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_agents), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + agent_service.ListAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + agent.Agent(), + ], + next_page_token="abc", + ), + agent_service.ListAgentsResponse( + agents=[], + next_page_token="def", + ), + agent_service.ListAgentsResponse( + agents=[ + agent.Agent(), + ], + next_page_token="ghi", + ), + agent_service.ListAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_agents( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, agent.Agent) for i in responses) + + +@pytest.mark.asyncio +async def test_list_agents_async_pages(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_agents), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + agent_service.ListAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + agent.Agent(), + ], + next_page_token="abc", + ), + agent_service.ListAgentsResponse( + agents=[], + next_page_token="def", + ), + agent_service.ListAgentsResponse( + agents=[ + agent.Agent(), + ], + next_page_token="ghi", + ), + agent_service.ListAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_agents(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.GetAgentRequest, + dict, + ], +) +def test_get_agent(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_agent), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = agent.Agent( + name="name_value", + display_name="display_name_value", + description="description_value", + instruction="instruction_value", + tools=["tools_value"], + child_agents=["child_agents_value"], + guardrails=["guardrails_value"], + etag="etag_value", + generated_summary="generated_summary_value", + ) + response = client.get_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.GetAgentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, agent.Agent) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.instruction == "instruction_value" + assert response.tools == ["tools_value"] + assert response.child_agents == ["child_agents_value"] + assert response.guardrails == ["guardrails_value"] + assert response.etag == "etag_value" + assert response.generated_summary == "generated_summary_value" + + +def test_get_agent_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.GetAgentRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_agent), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_agent(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.GetAgentRequest( + name="name_value", + ) + + +def test_get_agent_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_agent in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_agent] = mock_rpc + request = {} + client.get_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_agent(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_agent_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_agent + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_agent + ] = mock_rpc + + request = {} + await client.get_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_agent(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_agent_async( + transport: str = "grpc_asyncio", request_type=agent_service.GetAgentRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_agent), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent.Agent( + name="name_value", + display_name="display_name_value", + description="description_value", + instruction="instruction_value", + tools=["tools_value"], + child_agents=["child_agents_value"], + guardrails=["guardrails_value"], + etag="etag_value", + generated_summary="generated_summary_value", + ) + ) + response = await client.get_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.GetAgentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, agent.Agent) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.instruction == "instruction_value" + assert response.tools == ["tools_value"] + assert response.child_agents == ["child_agents_value"] + assert response.guardrails == ["guardrails_value"] + assert response.etag == "etag_value" + assert response.generated_summary == "generated_summary_value" + + +@pytest.mark.asyncio +async def test_get_agent_async_from_dict(): + await test_get_agent_async(request_type=dict) + + +def test_get_agent_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.GetAgentRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_agent), "__call__") as call: + call.return_value = agent.Agent() + client.get_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_agent_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.GetAgentRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_agent), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.Agent()) + await client.get_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_agent_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_agent), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = agent.Agent() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_agent( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_agent_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_agent( + agent_service.GetAgentRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_agent_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_agent), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = agent.Agent() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(agent.Agent()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_agent( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_agent_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_agent( + agent_service.GetAgentRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.CreateAgentRequest, + dict, + ], +) +def test_create_agent(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_agent), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_agent.Agent( + name="name_value", + display_name="display_name_value", + description="description_value", + instruction="instruction_value", + tools=["tools_value"], + child_agents=["child_agents_value"], + guardrails=["guardrails_value"], + etag="etag_value", + generated_summary="generated_summary_value", + ) + response = client.create_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.CreateAgentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_agent.Agent) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.instruction == "instruction_value" + assert response.tools == ["tools_value"] + assert response.child_agents == ["child_agents_value"] + assert response.guardrails == ["guardrails_value"] + assert response.etag == "etag_value" + assert response.generated_summary == "generated_summary_value" + + +def test_create_agent_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.CreateAgentRequest( + parent="parent_value", + agent_id="agent_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_agent), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_agent(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.CreateAgentRequest( + parent="parent_value", + agent_id="agent_id_value", + ) + + +def test_create_agent_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_agent in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_agent] = mock_rpc + request = {} + client.create_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_agent(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_agent_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_agent + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_agent + ] = mock_rpc + + request = {} + await client.create_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_agent(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_agent_async( + transport: str = "grpc_asyncio", request_type=agent_service.CreateAgentRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_agent), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_agent.Agent( + name="name_value", + display_name="display_name_value", + description="description_value", + instruction="instruction_value", + tools=["tools_value"], + child_agents=["child_agents_value"], + guardrails=["guardrails_value"], + etag="etag_value", + generated_summary="generated_summary_value", + ) + ) + response = await client.create_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.CreateAgentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_agent.Agent) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.instruction == "instruction_value" + assert response.tools == ["tools_value"] + assert response.child_agents == ["child_agents_value"] + assert response.guardrails == ["guardrails_value"] + assert response.etag == "etag_value" + assert response.generated_summary == "generated_summary_value" + + +@pytest.mark.asyncio +async def test_create_agent_async_from_dict(): + await test_create_agent_async(request_type=dict) + + +def test_create_agent_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.CreateAgentRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_agent), "__call__") as call: + call.return_value = gcc_agent.Agent() + client.create_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_agent_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.CreateAgentRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_agent), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcc_agent.Agent()) + await client.create_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_agent_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_agent), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_agent.Agent() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_agent( + parent="parent_value", + agent=gcc_agent.Agent(llm_agent=None), + agent_id="agent_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].agent + mock_val = gcc_agent.Agent(llm_agent=None) + assert arg == mock_val + arg = args[0].agent_id + mock_val = "agent_id_value" + assert arg == mock_val + + +def test_create_agent_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_agent( + agent_service.CreateAgentRequest(), + parent="parent_value", + agent=gcc_agent.Agent(llm_agent=None), + agent_id="agent_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_agent_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_agent), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_agent.Agent() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcc_agent.Agent()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_agent( + parent="parent_value", + agent=gcc_agent.Agent(llm_agent=None), + agent_id="agent_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].agent + mock_val = gcc_agent.Agent(llm_agent=None) + assert arg == mock_val + arg = args[0].agent_id + mock_val = "agent_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_agent_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_agent( + agent_service.CreateAgentRequest(), + parent="parent_value", + agent=gcc_agent.Agent(llm_agent=None), + agent_id="agent_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.UpdateAgentRequest, + dict, + ], +) +def test_update_agent(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_agent), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_agent.Agent( + name="name_value", + display_name="display_name_value", + description="description_value", + instruction="instruction_value", + tools=["tools_value"], + child_agents=["child_agents_value"], + guardrails=["guardrails_value"], + etag="etag_value", + generated_summary="generated_summary_value", + ) + response = client.update_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.UpdateAgentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_agent.Agent) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.instruction == "instruction_value" + assert response.tools == ["tools_value"] + assert response.child_agents == ["child_agents_value"] + assert response.guardrails == ["guardrails_value"] + assert response.etag == "etag_value" + assert response.generated_summary == "generated_summary_value" + + +def test_update_agent_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.UpdateAgentRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_agent), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_agent(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.UpdateAgentRequest() + + +def test_update_agent_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_agent in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_agent] = mock_rpc + request = {} + client.update_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_agent(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_agent_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_agent + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_agent + ] = mock_rpc + + request = {} + await client.update_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_agent(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_agent_async( + transport: str = "grpc_asyncio", request_type=agent_service.UpdateAgentRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_agent), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_agent.Agent( + name="name_value", + display_name="display_name_value", + description="description_value", + instruction="instruction_value", + tools=["tools_value"], + child_agents=["child_agents_value"], + guardrails=["guardrails_value"], + etag="etag_value", + generated_summary="generated_summary_value", + ) + ) + response = await client.update_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.UpdateAgentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_agent.Agent) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.instruction == "instruction_value" + assert response.tools == ["tools_value"] + assert response.child_agents == ["child_agents_value"] + assert response.guardrails == ["guardrails_value"] + assert response.etag == "etag_value" + assert response.generated_summary == "generated_summary_value" + + +@pytest.mark.asyncio +async def test_update_agent_async_from_dict(): + await test_update_agent_async(request_type=dict) + + +def test_update_agent_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.UpdateAgentRequest() + + request.agent.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_agent), "__call__") as call: + call.return_value = gcc_agent.Agent() + client.update_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "agent.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_agent_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.UpdateAgentRequest() + + request.agent.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_agent), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcc_agent.Agent()) + await client.update_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "agent.name=name_value", + ) in kw["metadata"] + + +def test_update_agent_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_agent), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_agent.Agent() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_agent( + agent=gcc_agent.Agent(llm_agent=None), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].agent + mock_val = gcc_agent.Agent(llm_agent=None) + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_agent_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_agent( + agent_service.UpdateAgentRequest(), + agent=gcc_agent.Agent(llm_agent=None), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_agent_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_agent), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_agent.Agent() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcc_agent.Agent()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_agent( + agent=gcc_agent.Agent(llm_agent=None), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].agent + mock_val = gcc_agent.Agent(llm_agent=None) + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_agent_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_agent( + agent_service.UpdateAgentRequest(), + agent=gcc_agent.Agent(llm_agent=None), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.DeleteAgentRequest, + dict, + ], +) +def test_delete_agent(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_agent), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.DeleteAgentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_agent_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.DeleteAgentRequest( + name="name_value", + etag="etag_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_agent), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_agent(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.DeleteAgentRequest( + name="name_value", + etag="etag_value", + ) + + +def test_delete_agent_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_agent in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_agent] = mock_rpc + request = {} + client.delete_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_agent(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_agent_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_agent + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_agent + ] = mock_rpc + + request = {} + await client.delete_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_agent(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_agent_async( + transport: str = "grpc_asyncio", request_type=agent_service.DeleteAgentRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_agent), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.DeleteAgentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_agent_async_from_dict(): + await test_delete_agent_async(request_type=dict) + + +def test_delete_agent_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.DeleteAgentRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_agent), "__call__") as call: + call.return_value = None + client.delete_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_agent_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.DeleteAgentRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_agent), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_agent_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_agent), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_agent( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_agent_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_agent( + agent_service.DeleteAgentRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_agent_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_agent), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_agent( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_agent_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_agent( + agent_service.DeleteAgentRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.ListExamplesRequest, + dict, + ], +) +def test_list_examples(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_examples), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = agent_service.ListExamplesResponse( + next_page_token="next_page_token_value", + ) + response = client.list_examples(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.ListExamplesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListExamplesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_examples_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.ListExamplesRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_examples), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_examples(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.ListExamplesRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + +def test_list_examples_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_examples in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_examples] = mock_rpc + request = {} + client.list_examples(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_examples(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_examples_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_examples + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_examples + ] = mock_rpc + + request = {} + await client.list_examples(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_examples(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_examples_async( + transport: str = "grpc_asyncio", request_type=agent_service.ListExamplesRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_examples), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent_service.ListExamplesResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_examples(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.ListExamplesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListExamplesAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_examples_async_from_dict(): + await test_list_examples_async(request_type=dict) + + +def test_list_examples_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.ListExamplesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_examples), "__call__") as call: + call.return_value = agent_service.ListExamplesResponse() + client.list_examples(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_examples_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.ListExamplesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_examples), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent_service.ListExamplesResponse() + ) + await client.list_examples(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_examples_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_examples), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = agent_service.ListExamplesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_examples( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_examples_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_examples( + agent_service.ListExamplesRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_examples_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_examples), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = agent_service.ListExamplesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent_service.ListExamplesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_examples( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_examples_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_examples( + agent_service.ListExamplesRequest(), + parent="parent_value", + ) + + +def test_list_examples_pager(transport_name: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_examples), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + agent_service.ListExamplesResponse( + examples=[ + example.Example(), + example.Example(), + example.Example(), + ], + next_page_token="abc", + ), + agent_service.ListExamplesResponse( + examples=[], + next_page_token="def", + ), + agent_service.ListExamplesResponse( + examples=[ + example.Example(), + ], + next_page_token="ghi", + ), + agent_service.ListExamplesResponse( + examples=[ + example.Example(), + example.Example(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_examples(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, example.Example) for i in results) + + +def test_list_examples_pages(transport_name: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_examples), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + agent_service.ListExamplesResponse( + examples=[ + example.Example(), + example.Example(), + example.Example(), + ], + next_page_token="abc", + ), + agent_service.ListExamplesResponse( + examples=[], + next_page_token="def", + ), + agent_service.ListExamplesResponse( + examples=[ + example.Example(), + ], + next_page_token="ghi", + ), + agent_service.ListExamplesResponse( + examples=[ + example.Example(), + example.Example(), + ], + ), + RuntimeError, + ) + pages = list(client.list_examples(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_examples_async_pager(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_examples), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + agent_service.ListExamplesResponse( + examples=[ + example.Example(), + example.Example(), + example.Example(), + ], + next_page_token="abc", + ), + agent_service.ListExamplesResponse( + examples=[], + next_page_token="def", + ), + agent_service.ListExamplesResponse( + examples=[ + example.Example(), + ], + next_page_token="ghi", + ), + agent_service.ListExamplesResponse( + examples=[ + example.Example(), + example.Example(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_examples( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, example.Example) for i in responses) + + +@pytest.mark.asyncio +async def test_list_examples_async_pages(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_examples), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + agent_service.ListExamplesResponse( + examples=[ + example.Example(), + example.Example(), + example.Example(), + ], + next_page_token="abc", + ), + agent_service.ListExamplesResponse( + examples=[], + next_page_token="def", + ), + agent_service.ListExamplesResponse( + examples=[ + example.Example(), + ], + next_page_token="ghi", + ), + agent_service.ListExamplesResponse( + examples=[ + example.Example(), + example.Example(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_examples(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.GetExampleRequest, + dict, + ], +) +def test_get_example(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_example), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = example.Example( + name="name_value", + display_name="display_name_value", + description="description_value", + entry_agent="entry_agent_value", + invalid=True, + etag="etag_value", + ) + response = client.get_example(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.GetExampleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, example.Example) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.entry_agent == "entry_agent_value" + assert response.invalid is True + assert response.etag == "etag_value" + + +def test_get_example_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.GetExampleRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_example), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_example(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.GetExampleRequest( + name="name_value", + ) + + +def test_get_example_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_example in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_example] = mock_rpc + request = {} + client.get_example(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_example(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_example_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_example + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_example + ] = mock_rpc + + request = {} + await client.get_example(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_example(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_example_async( + transport: str = "grpc_asyncio", request_type=agent_service.GetExampleRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_example), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + example.Example( + name="name_value", + display_name="display_name_value", + description="description_value", + entry_agent="entry_agent_value", + invalid=True, + etag="etag_value", + ) + ) + response = await client.get_example(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.GetExampleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, example.Example) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.entry_agent == "entry_agent_value" + assert response.invalid is True + assert response.etag == "etag_value" + + +@pytest.mark.asyncio +async def test_get_example_async_from_dict(): + await test_get_example_async(request_type=dict) + + +def test_get_example_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.GetExampleRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_example), "__call__") as call: + call.return_value = example.Example() + client.get_example(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_example_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.GetExampleRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_example), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(example.Example()) + await client.get_example(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_example_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_example), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = example.Example() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_example( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_example_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_example( + agent_service.GetExampleRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_example_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_example), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = example.Example() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(example.Example()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_example( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_example_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_example( + agent_service.GetExampleRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.CreateExampleRequest, + dict, + ], +) +def test_create_example(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_example), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_example.Example( + name="name_value", + display_name="display_name_value", + description="description_value", + entry_agent="entry_agent_value", + invalid=True, + etag="etag_value", + ) + response = client.create_example(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.CreateExampleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_example.Example) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.entry_agent == "entry_agent_value" + assert response.invalid is True + assert response.etag == "etag_value" + + +def test_create_example_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.CreateExampleRequest( + parent="parent_value", + example_id="example_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_example), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_example(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.CreateExampleRequest( + parent="parent_value", + example_id="example_id_value", + ) + + +def test_create_example_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_example in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_example] = mock_rpc + request = {} + client.create_example(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_example(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_example_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_example + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_example + ] = mock_rpc + + request = {} + await client.create_example(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_example(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_example_async( + transport: str = "grpc_asyncio", request_type=agent_service.CreateExampleRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_example), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_example.Example( + name="name_value", + display_name="display_name_value", + description="description_value", + entry_agent="entry_agent_value", + invalid=True, + etag="etag_value", + ) + ) + response = await client.create_example(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.CreateExampleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_example.Example) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.entry_agent == "entry_agent_value" + assert response.invalid is True + assert response.etag == "etag_value" + + +@pytest.mark.asyncio +async def test_create_example_async_from_dict(): + await test_create_example_async(request_type=dict) + + +def test_create_example_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.CreateExampleRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_example), "__call__") as call: + call.return_value = gcc_example.Example() + client.create_example(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_example_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.CreateExampleRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_example), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcc_example.Example()) + await client.create_example(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_example_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_example), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_example.Example() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_example( + parent="parent_value", + example=gcc_example.Example(name="name_value"), + example_id="example_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].example + mock_val = gcc_example.Example(name="name_value") + assert arg == mock_val + arg = args[0].example_id + mock_val = "example_id_value" + assert arg == mock_val + + +def test_create_example_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_example( + agent_service.CreateExampleRequest(), + parent="parent_value", + example=gcc_example.Example(name="name_value"), + example_id="example_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_example_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_example), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_example.Example() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcc_example.Example()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_example( + parent="parent_value", + example=gcc_example.Example(name="name_value"), + example_id="example_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].example + mock_val = gcc_example.Example(name="name_value") + assert arg == mock_val + arg = args[0].example_id + mock_val = "example_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_example_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_example( + agent_service.CreateExampleRequest(), + parent="parent_value", + example=gcc_example.Example(name="name_value"), + example_id="example_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.UpdateExampleRequest, + dict, + ], +) +def test_update_example(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_example), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_example.Example( + name="name_value", + display_name="display_name_value", + description="description_value", + entry_agent="entry_agent_value", + invalid=True, + etag="etag_value", + ) + response = client.update_example(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.UpdateExampleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_example.Example) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.entry_agent == "entry_agent_value" + assert response.invalid is True + assert response.etag == "etag_value" + + +def test_update_example_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.UpdateExampleRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_example), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_example(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.UpdateExampleRequest() + + +def test_update_example_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_example in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_example] = mock_rpc + request = {} + client.update_example(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_example(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_example_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_example + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_example + ] = mock_rpc + + request = {} + await client.update_example(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_example(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_example_async( + transport: str = "grpc_asyncio", request_type=agent_service.UpdateExampleRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_example), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_example.Example( + name="name_value", + display_name="display_name_value", + description="description_value", + entry_agent="entry_agent_value", + invalid=True, + etag="etag_value", + ) + ) + response = await client.update_example(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.UpdateExampleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_example.Example) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.entry_agent == "entry_agent_value" + assert response.invalid is True + assert response.etag == "etag_value" + + +@pytest.mark.asyncio +async def test_update_example_async_from_dict(): + await test_update_example_async(request_type=dict) + + +def test_update_example_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.UpdateExampleRequest() + + request.example.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_example), "__call__") as call: + call.return_value = gcc_example.Example() + client.update_example(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "example.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_example_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.UpdateExampleRequest() + + request.example.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_example), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcc_example.Example()) + await client.update_example(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "example.name=name_value", + ) in kw["metadata"] + + +def test_update_example_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_example), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_example.Example() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_example( + example=gcc_example.Example(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].example + mock_val = gcc_example.Example(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_example_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_example( + agent_service.UpdateExampleRequest(), + example=gcc_example.Example(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_example_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_example), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_example.Example() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcc_example.Example()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_example( + example=gcc_example.Example(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].example + mock_val = gcc_example.Example(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_example_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_example( + agent_service.UpdateExampleRequest(), + example=gcc_example.Example(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.DeleteExampleRequest, + dict, + ], +) +def test_delete_example(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_example), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_example(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.DeleteExampleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_example_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.DeleteExampleRequest( + name="name_value", + etag="etag_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_example), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_example(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.DeleteExampleRequest( + name="name_value", + etag="etag_value", + ) + + +def test_delete_example_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_example in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_example] = mock_rpc + request = {} + client.delete_example(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_example(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_example_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_example + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_example + ] = mock_rpc + + request = {} + await client.delete_example(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_example(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_example_async( + transport: str = "grpc_asyncio", request_type=agent_service.DeleteExampleRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_example), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_example(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.DeleteExampleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_example_async_from_dict(): + await test_delete_example_async(request_type=dict) + + +def test_delete_example_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.DeleteExampleRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_example), "__call__") as call: + call.return_value = None + client.delete_example(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_example_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.DeleteExampleRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_example), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_example(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_example_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_example), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_example( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_example_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_example( + agent_service.DeleteExampleRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_example_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_example), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_example( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_example_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_example( + agent_service.DeleteExampleRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.ListToolsRequest, + dict, + ], +) +def test_list_tools(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_tools), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = agent_service.ListToolsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_tools(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.ListToolsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListToolsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_tools_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.ListToolsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_tools), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_tools(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.ListToolsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + +def test_list_tools_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_tools in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_tools] = mock_rpc + request = {} + client.list_tools(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_tools(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_tools_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_tools + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_tools + ] = mock_rpc + + request = {} + await client.list_tools(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_tools(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_tools_async( + transport: str = "grpc_asyncio", request_type=agent_service.ListToolsRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_tools), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent_service.ListToolsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_tools(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.ListToolsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListToolsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_tools_async_from_dict(): + await test_list_tools_async(request_type=dict) + + +def test_list_tools_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.ListToolsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_tools), "__call__") as call: + call.return_value = agent_service.ListToolsResponse() + client.list_tools(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_tools_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.ListToolsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_tools), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent_service.ListToolsResponse() + ) + await client.list_tools(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_tools_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_tools), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = agent_service.ListToolsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_tools( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_tools_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_tools( + agent_service.ListToolsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_tools_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_tools), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = agent_service.ListToolsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent_service.ListToolsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_tools( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_tools_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_tools( + agent_service.ListToolsRequest(), + parent="parent_value", + ) + + +def test_list_tools_pager(transport_name: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_tools), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + agent_service.ListToolsResponse( + tools=[ + tool.Tool(), + tool.Tool(), + tool.Tool(), + ], + next_page_token="abc", + ), + agent_service.ListToolsResponse( + tools=[], + next_page_token="def", + ), + agent_service.ListToolsResponse( + tools=[ + tool.Tool(), + ], + next_page_token="ghi", + ), + agent_service.ListToolsResponse( + tools=[ + tool.Tool(), + tool.Tool(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_tools(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, tool.Tool) for i in results) + + +def test_list_tools_pages(transport_name: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_tools), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + agent_service.ListToolsResponse( + tools=[ + tool.Tool(), + tool.Tool(), + tool.Tool(), + ], + next_page_token="abc", + ), + agent_service.ListToolsResponse( + tools=[], + next_page_token="def", + ), + agent_service.ListToolsResponse( + tools=[ + tool.Tool(), + ], + next_page_token="ghi", + ), + agent_service.ListToolsResponse( + tools=[ + tool.Tool(), + tool.Tool(), + ], + ), + RuntimeError, + ) + pages = list(client.list_tools(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_tools_async_pager(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tools), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + agent_service.ListToolsResponse( + tools=[ + tool.Tool(), + tool.Tool(), + tool.Tool(), + ], + next_page_token="abc", + ), + agent_service.ListToolsResponse( + tools=[], + next_page_token="def", + ), + agent_service.ListToolsResponse( + tools=[ + tool.Tool(), + ], + next_page_token="ghi", + ), + agent_service.ListToolsResponse( + tools=[ + tool.Tool(), + tool.Tool(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_tools( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, tool.Tool) for i in responses) + + +@pytest.mark.asyncio +async def test_list_tools_async_pages(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_tools), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + agent_service.ListToolsResponse( + tools=[ + tool.Tool(), + tool.Tool(), + tool.Tool(), + ], + next_page_token="abc", + ), + agent_service.ListToolsResponse( + tools=[], + next_page_token="def", + ), + agent_service.ListToolsResponse( + tools=[ + tool.Tool(), + ], + next_page_token="ghi", + ), + agent_service.ListToolsResponse( + tools=[ + tool.Tool(), + tool.Tool(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_tools(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.GetToolRequest, + dict, + ], +) +def test_get_tool(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = tool.Tool( + name="name_value", + display_name="display_name_value", + execution_type=common.ExecutionType.SYNCHRONOUS, + etag="etag_value", + generated_summary="generated_summary_value", + ) + response = client.get_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.GetToolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, tool.Tool) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.execution_type == common.ExecutionType.SYNCHRONOUS + assert response.etag == "etag_value" + assert response.generated_summary == "generated_summary_value" + + +def test_get_tool_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.GetToolRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_tool), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_tool(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.GetToolRequest( + name="name_value", + ) + + +def test_get_tool_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_tool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_tool] = mock_rpc + request = {} + client.get_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_tool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_tool_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_tool + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_tool + ] = mock_rpc + + request = {} + await client.get_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_tool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_tool_async( + transport: str = "grpc_asyncio", request_type=agent_service.GetToolRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + tool.Tool( + name="name_value", + display_name="display_name_value", + execution_type=common.ExecutionType.SYNCHRONOUS, + etag="etag_value", + generated_summary="generated_summary_value", + ) + ) + response = await client.get_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.GetToolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, tool.Tool) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.execution_type == common.ExecutionType.SYNCHRONOUS + assert response.etag == "etag_value" + assert response.generated_summary == "generated_summary_value" + + +@pytest.mark.asyncio +async def test_get_tool_async_from_dict(): + await test_get_tool_async(request_type=dict) + + +def test_get_tool_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.GetToolRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_tool), "__call__") as call: + call.return_value = tool.Tool() + client.get_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_tool_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.GetToolRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_tool), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tool.Tool()) + await client.get_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_tool_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = tool.Tool() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_tool( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_tool_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_tool( + agent_service.GetToolRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_tool_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = tool.Tool() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tool.Tool()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_tool( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_tool_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_tool( + agent_service.GetToolRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.ListConversationsRequest, + dict, + ], +) +def test_list_conversations(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = agent_service.ListConversationsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_conversations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.ListConversationsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListConversationsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_conversations_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.ListConversationsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_conversations(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.ListConversationsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + ) + + +def test_list_conversations_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_conversations in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_conversations] = ( + mock_rpc + ) + request = {} + client.list_conversations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_conversations(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_conversations_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_conversations + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_conversations + ] = mock_rpc + + request = {} + await client.list_conversations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_conversations(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_conversations_async( + transport: str = "grpc_asyncio", request_type=agent_service.ListConversationsRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent_service.ListConversationsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_conversations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.ListConversationsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListConversationsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_conversations_async_from_dict(): + await test_list_conversations_async(request_type=dict) + + +def test_list_conversations_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.ListConversationsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), "__call__" + ) as call: + call.return_value = agent_service.ListConversationsResponse() + client.list_conversations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_conversations_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.ListConversationsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent_service.ListConversationsResponse() + ) + await client.list_conversations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_conversations_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = agent_service.ListConversationsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_conversations( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_conversations_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_conversations( + agent_service.ListConversationsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_conversations_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = agent_service.ListConversationsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent_service.ListConversationsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_conversations( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_conversations_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_conversations( + agent_service.ListConversationsRequest(), + parent="parent_value", + ) + + +def test_list_conversations_pager(transport_name: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + agent_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + conversation.Conversation(), + ], + next_page_token="abc", + ), + agent_service.ListConversationsResponse( + conversations=[], + next_page_token="def", + ), + agent_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + ], + next_page_token="ghi", + ), + agent_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_conversations(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, conversation.Conversation) for i in results) + + +def test_list_conversations_pages(transport_name: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + agent_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + conversation.Conversation(), + ], + next_page_token="abc", + ), + agent_service.ListConversationsResponse( + conversations=[], + next_page_token="def", + ), + agent_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + ], + next_page_token="ghi", + ), + agent_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + ], + ), + RuntimeError, + ) + pages = list(client.list_conversations(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_conversations_async_pager(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + agent_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + conversation.Conversation(), + ], + next_page_token="abc", + ), + agent_service.ListConversationsResponse( + conversations=[], + next_page_token="def", + ), + agent_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + ], + next_page_token="ghi", + ), + agent_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_conversations( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, conversation.Conversation) for i in responses) + + +@pytest.mark.asyncio +async def test_list_conversations_async_pages(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + agent_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + conversation.Conversation(), + ], + next_page_token="abc", + ), + agent_service.ListConversationsResponse( + conversations=[], + next_page_token="def", + ), + agent_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + ], + next_page_token="ghi", + ), + agent_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_conversations(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.GetConversationRequest, + dict, + ], +) +def test_get_conversation(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_conversation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = conversation.Conversation( + name="name_value", + turn_count=1105, + channel_type=conversation.Conversation.ChannelType.TEXT, + source=conversation.Conversation.Source.LIVE, + input_types=[conversation.Conversation.InputType.INPUT_TYPE_TEXT], + entry_agent="entry_agent_value", + deployment="deployment_value", + app_version="app_version_value", + language_code="language_code_value", + ) + response = client.get_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.GetConversationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, conversation.Conversation) + assert response.name == "name_value" + assert response.turn_count == 1105 + assert response.channel_type == conversation.Conversation.ChannelType.TEXT + assert response.source == conversation.Conversation.Source.LIVE + assert response.input_types == [conversation.Conversation.InputType.INPUT_TYPE_TEXT] + assert response.entry_agent == "entry_agent_value" + assert response.deployment == "deployment_value" + assert response.app_version == "app_version_value" + assert response.language_code == "language_code_value" + + +def test_get_conversation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.GetConversationRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_conversation), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_conversation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.GetConversationRequest( + name="name_value", + ) + + +def test_get_conversation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_conversation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_conversation] = ( + mock_rpc + ) + request = {} + client.get_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_conversation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_conversation_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_conversation + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_conversation + ] = mock_rpc + + request = {} + await client.get_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_conversation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_conversation_async( + transport: str = "grpc_asyncio", request_type=agent_service.GetConversationRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_conversation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + conversation.Conversation( + name="name_value", + turn_count=1105, + channel_type=conversation.Conversation.ChannelType.TEXT, + source=conversation.Conversation.Source.LIVE, + input_types=[conversation.Conversation.InputType.INPUT_TYPE_TEXT], + entry_agent="entry_agent_value", + deployment="deployment_value", + app_version="app_version_value", + language_code="language_code_value", + ) + ) + response = await client.get_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.GetConversationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, conversation.Conversation) + assert response.name == "name_value" + assert response.turn_count == 1105 + assert response.channel_type == conversation.Conversation.ChannelType.TEXT + assert response.source == conversation.Conversation.Source.LIVE + assert response.input_types == [conversation.Conversation.InputType.INPUT_TYPE_TEXT] + assert response.entry_agent == "entry_agent_value" + assert response.deployment == "deployment_value" + assert response.app_version == "app_version_value" + assert response.language_code == "language_code_value" + + +@pytest.mark.asyncio +async def test_get_conversation_async_from_dict(): + await test_get_conversation_async(request_type=dict) + + +def test_get_conversation_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.GetConversationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_conversation), "__call__") as call: + call.return_value = conversation.Conversation() + client.get_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_conversation_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.GetConversationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_conversation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + conversation.Conversation() + ) + await client.get_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_conversation_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_conversation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = conversation.Conversation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_conversation( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_conversation_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_conversation( + agent_service.GetConversationRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_conversation_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_conversation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = conversation.Conversation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + conversation.Conversation() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_conversation( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_conversation_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_conversation( + agent_service.GetConversationRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.DeleteConversationRequest, + dict, + ], +) +def test_delete_conversation(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.DeleteConversationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_conversation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.DeleteConversationRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversation), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_conversation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.DeleteConversationRequest( + name="name_value", + ) + + +def test_delete_conversation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_conversation in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_conversation] = ( + mock_rpc + ) + request = {} + client.delete_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_conversation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_conversation_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_conversation + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_conversation + ] = mock_rpc + + request = {} + await client.delete_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_conversation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_conversation_async( + transport: str = "grpc_asyncio", + request_type=agent_service.DeleteConversationRequest, +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.DeleteConversationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_conversation_async_from_dict(): + await test_delete_conversation_async(request_type=dict) + + +def test_delete_conversation_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.DeleteConversationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversation), "__call__" + ) as call: + call.return_value = None + client.delete_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_conversation_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.DeleteConversationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversation), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_conversation_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_conversation( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_conversation_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_conversation( + agent_service.DeleteConversationRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_conversation_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_conversation( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_conversation_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_conversation( + agent_service.DeleteConversationRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.BatchDeleteConversationsRequest, + dict, + ], +) +def test_batch_delete_conversations(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_conversations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.batch_delete_conversations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.BatchDeleteConversationsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_batch_delete_conversations_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.BatchDeleteConversationsRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_conversations), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.batch_delete_conversations(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.BatchDeleteConversationsRequest( + parent="parent_value", + ) + + +def test_batch_delete_conversations_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.batch_delete_conversations + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.batch_delete_conversations + ] = mock_rpc + request = {} + client.batch_delete_conversations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.batch_delete_conversations(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_batch_delete_conversations_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.batch_delete_conversations + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.batch_delete_conversations + ] = mock_rpc + + request = {} + await client.batch_delete_conversations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.batch_delete_conversations(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_batch_delete_conversations_async( + transport: str = "grpc_asyncio", + request_type=agent_service.BatchDeleteConversationsRequest, +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_conversations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.batch_delete_conversations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.BatchDeleteConversationsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_batch_delete_conversations_async_from_dict(): + await test_batch_delete_conversations_async(request_type=dict) + + +def test_batch_delete_conversations_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.BatchDeleteConversationsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_conversations), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.batch_delete_conversations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_batch_delete_conversations_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.BatchDeleteConversationsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_conversations), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.batch_delete_conversations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_batch_delete_conversations_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_conversations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_delete_conversations( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_batch_delete_conversations_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_delete_conversations( + agent_service.BatchDeleteConversationsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_batch_delete_conversations_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_conversations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.batch_delete_conversations( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_batch_delete_conversations_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.batch_delete_conversations( + agent_service.BatchDeleteConversationsRequest(), + parent="parent_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.CreateToolRequest, + dict, + ], +) +def test_create_tool(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_tool.Tool( + name="name_value", + display_name="display_name_value", + execution_type=common.ExecutionType.SYNCHRONOUS, + etag="etag_value", + generated_summary="generated_summary_value", + ) + response = client.create_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.CreateToolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_tool.Tool) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.execution_type == common.ExecutionType.SYNCHRONOUS + assert response.etag == "etag_value" + assert response.generated_summary == "generated_summary_value" + + +def test_create_tool_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.CreateToolRequest( + parent="parent_value", + tool_id="tool_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_tool), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_tool(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.CreateToolRequest( + parent="parent_value", + tool_id="tool_id_value", + ) + + +def test_create_tool_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_tool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_tool] = mock_rpc + request = {} + client.create_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_tool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_tool_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_tool + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_tool + ] = mock_rpc + + request = {} + await client.create_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_tool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_tool_async( + transport: str = "grpc_asyncio", request_type=agent_service.CreateToolRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_tool.Tool( + name="name_value", + display_name="display_name_value", + execution_type=common.ExecutionType.SYNCHRONOUS, + etag="etag_value", + generated_summary="generated_summary_value", + ) + ) + response = await client.create_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.CreateToolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_tool.Tool) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.execution_type == common.ExecutionType.SYNCHRONOUS + assert response.etag == "etag_value" + assert response.generated_summary == "generated_summary_value" + + +@pytest.mark.asyncio +async def test_create_tool_async_from_dict(): + await test_create_tool_async(request_type=dict) + + +def test_create_tool_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.CreateToolRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_tool), "__call__") as call: + call.return_value = gcc_tool.Tool() + client.create_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_tool_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.CreateToolRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_tool), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcc_tool.Tool()) + await client.create_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_tool_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_tool.Tool() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_tool( + parent="parent_value", + tool=gcc_tool.Tool( + client_function=client_function.ClientFunction(name="name_value") + ), + tool_id="tool_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].tool + mock_val = gcc_tool.Tool( + client_function=client_function.ClientFunction(name="name_value") + ) + assert arg == mock_val + arg = args[0].tool_id + mock_val = "tool_id_value" + assert arg == mock_val + + +def test_create_tool_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_tool( + agent_service.CreateToolRequest(), + parent="parent_value", + tool=gcc_tool.Tool( + client_function=client_function.ClientFunction(name="name_value") + ), + tool_id="tool_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_tool_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_tool.Tool() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcc_tool.Tool()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_tool( + parent="parent_value", + tool=gcc_tool.Tool( + client_function=client_function.ClientFunction(name="name_value") + ), + tool_id="tool_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].tool + mock_val = gcc_tool.Tool( + client_function=client_function.ClientFunction(name="name_value") + ) + assert arg == mock_val + arg = args[0].tool_id + mock_val = "tool_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_tool_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_tool( + agent_service.CreateToolRequest(), + parent="parent_value", + tool=gcc_tool.Tool( + client_function=client_function.ClientFunction(name="name_value") + ), + tool_id="tool_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.UpdateToolRequest, + dict, + ], +) +def test_update_tool(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_tool.Tool( + name="name_value", + display_name="display_name_value", + execution_type=common.ExecutionType.SYNCHRONOUS, + etag="etag_value", + generated_summary="generated_summary_value", + ) + response = client.update_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.UpdateToolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_tool.Tool) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.execution_type == common.ExecutionType.SYNCHRONOUS + assert response.etag == "etag_value" + assert response.generated_summary == "generated_summary_value" + + +def test_update_tool_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.UpdateToolRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_tool), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_tool(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.UpdateToolRequest() + + +def test_update_tool_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_tool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_tool] = mock_rpc + request = {} + client.update_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_tool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_tool_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_tool + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_tool + ] = mock_rpc + + request = {} + await client.update_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_tool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_tool_async( + transport: str = "grpc_asyncio", request_type=agent_service.UpdateToolRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_tool.Tool( + name="name_value", + display_name="display_name_value", + execution_type=common.ExecutionType.SYNCHRONOUS, + etag="etag_value", + generated_summary="generated_summary_value", + ) + ) + response = await client.update_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.UpdateToolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_tool.Tool) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.execution_type == common.ExecutionType.SYNCHRONOUS + assert response.etag == "etag_value" + assert response.generated_summary == "generated_summary_value" + + +@pytest.mark.asyncio +async def test_update_tool_async_from_dict(): + await test_update_tool_async(request_type=dict) + + +def test_update_tool_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.UpdateToolRequest() + + request.tool.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_tool), "__call__") as call: + call.return_value = gcc_tool.Tool() + client.update_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "tool.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_tool_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.UpdateToolRequest() + + request.tool.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_tool), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcc_tool.Tool()) + await client.update_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "tool.name=name_value", + ) in kw["metadata"] + + +def test_update_tool_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_tool.Tool() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_tool( + tool=gcc_tool.Tool( + client_function=client_function.ClientFunction(name="name_value") + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].tool + mock_val = gcc_tool.Tool( + client_function=client_function.ClientFunction(name="name_value") + ) + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_tool_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_tool( + agent_service.UpdateToolRequest(), + tool=gcc_tool.Tool( + client_function=client_function.ClientFunction(name="name_value") + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_tool_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_tool.Tool() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcc_tool.Tool()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_tool( + tool=gcc_tool.Tool( + client_function=client_function.ClientFunction(name="name_value") + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].tool + mock_val = gcc_tool.Tool( + client_function=client_function.ClientFunction(name="name_value") + ) + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_tool_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_tool( + agent_service.UpdateToolRequest(), + tool=gcc_tool.Tool( + client_function=client_function.ClientFunction(name="name_value") + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.DeleteToolRequest, + dict, + ], +) +def test_delete_tool(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.DeleteToolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_tool_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.DeleteToolRequest( + name="name_value", + etag="etag_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_tool), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_tool(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.DeleteToolRequest( + name="name_value", + etag="etag_value", + ) + + +def test_delete_tool_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_tool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_tool] = mock_rpc + request = {} + client.delete_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_tool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_tool_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_tool + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_tool + ] = mock_rpc + + request = {} + await client.delete_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_tool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_tool_async( + transport: str = "grpc_asyncio", request_type=agent_service.DeleteToolRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.DeleteToolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_tool_async_from_dict(): + await test_delete_tool_async(request_type=dict) + + +def test_delete_tool_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.DeleteToolRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_tool), "__call__") as call: + call.return_value = None + client.delete_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_tool_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.DeleteToolRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_tool), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_tool_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_tool( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_tool_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_tool( + agent_service.DeleteToolRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_tool_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_tool( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_tool_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_tool( + agent_service.DeleteToolRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.ListGuardrailsRequest, + dict, + ], +) +def test_list_guardrails(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_guardrails), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = agent_service.ListGuardrailsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_guardrails(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.ListGuardrailsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListGuardrailsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_guardrails_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.ListGuardrailsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_guardrails), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_guardrails(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.ListGuardrailsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + +def test_list_guardrails_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_guardrails in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_guardrails] = mock_rpc + request = {} + client.list_guardrails(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_guardrails(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_guardrails_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_guardrails + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_guardrails + ] = mock_rpc + + request = {} + await client.list_guardrails(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_guardrails(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_guardrails_async( + transport: str = "grpc_asyncio", request_type=agent_service.ListGuardrailsRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_guardrails), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent_service.ListGuardrailsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_guardrails(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.ListGuardrailsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListGuardrailsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_guardrails_async_from_dict(): + await test_list_guardrails_async(request_type=dict) + + +def test_list_guardrails_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.ListGuardrailsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_guardrails), "__call__") as call: + call.return_value = agent_service.ListGuardrailsResponse() + client.list_guardrails(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_guardrails_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.ListGuardrailsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_guardrails), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent_service.ListGuardrailsResponse() + ) + await client.list_guardrails(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_guardrails_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_guardrails), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = agent_service.ListGuardrailsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_guardrails( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_guardrails_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_guardrails( + agent_service.ListGuardrailsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_guardrails_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_guardrails), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = agent_service.ListGuardrailsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent_service.ListGuardrailsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_guardrails( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_guardrails_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_guardrails( + agent_service.ListGuardrailsRequest(), + parent="parent_value", + ) + + +def test_list_guardrails_pager(transport_name: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_guardrails), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + agent_service.ListGuardrailsResponse( + guardrails=[ + guardrail.Guardrail(), + guardrail.Guardrail(), + guardrail.Guardrail(), + ], + next_page_token="abc", + ), + agent_service.ListGuardrailsResponse( + guardrails=[], + next_page_token="def", + ), + agent_service.ListGuardrailsResponse( + guardrails=[ + guardrail.Guardrail(), + ], + next_page_token="ghi", + ), + agent_service.ListGuardrailsResponse( + guardrails=[ + guardrail.Guardrail(), + guardrail.Guardrail(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_guardrails(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, guardrail.Guardrail) for i in results) + + +def test_list_guardrails_pages(transport_name: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_guardrails), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + agent_service.ListGuardrailsResponse( + guardrails=[ + guardrail.Guardrail(), + guardrail.Guardrail(), + guardrail.Guardrail(), + ], + next_page_token="abc", + ), + agent_service.ListGuardrailsResponse( + guardrails=[], + next_page_token="def", + ), + agent_service.ListGuardrailsResponse( + guardrails=[ + guardrail.Guardrail(), + ], + next_page_token="ghi", + ), + agent_service.ListGuardrailsResponse( + guardrails=[ + guardrail.Guardrail(), + guardrail.Guardrail(), + ], + ), + RuntimeError, + ) + pages = list(client.list_guardrails(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_guardrails_async_pager(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_guardrails), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + agent_service.ListGuardrailsResponse( + guardrails=[ + guardrail.Guardrail(), + guardrail.Guardrail(), + guardrail.Guardrail(), + ], + next_page_token="abc", + ), + agent_service.ListGuardrailsResponse( + guardrails=[], + next_page_token="def", + ), + agent_service.ListGuardrailsResponse( + guardrails=[ + guardrail.Guardrail(), + ], + next_page_token="ghi", + ), + agent_service.ListGuardrailsResponse( + guardrails=[ + guardrail.Guardrail(), + guardrail.Guardrail(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_guardrails( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, guardrail.Guardrail) for i in responses) + + +@pytest.mark.asyncio +async def test_list_guardrails_async_pages(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_guardrails), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + agent_service.ListGuardrailsResponse( + guardrails=[ + guardrail.Guardrail(), + guardrail.Guardrail(), + guardrail.Guardrail(), + ], + next_page_token="abc", + ), + agent_service.ListGuardrailsResponse( + guardrails=[], + next_page_token="def", + ), + agent_service.ListGuardrailsResponse( + guardrails=[ + guardrail.Guardrail(), + ], + next_page_token="ghi", + ), + agent_service.ListGuardrailsResponse( + guardrails=[ + guardrail.Guardrail(), + guardrail.Guardrail(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_guardrails(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.GetGuardrailRequest, + dict, + ], +) +def test_get_guardrail(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_guardrail), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = guardrail.Guardrail( + name="name_value", + display_name="display_name_value", + description="description_value", + enabled=True, + etag="etag_value", + ) + response = client.get_guardrail(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.GetGuardrailRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, guardrail.Guardrail) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.enabled is True + assert response.etag == "etag_value" + + +def test_get_guardrail_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.GetGuardrailRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_guardrail), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_guardrail(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.GetGuardrailRequest( + name="name_value", + ) + + +def test_get_guardrail_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_guardrail in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_guardrail] = mock_rpc + request = {} + client.get_guardrail(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_guardrail(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_guardrail_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_guardrail + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_guardrail + ] = mock_rpc + + request = {} + await client.get_guardrail(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_guardrail(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_guardrail_async( + transport: str = "grpc_asyncio", request_type=agent_service.GetGuardrailRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_guardrail), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + guardrail.Guardrail( + name="name_value", + display_name="display_name_value", + description="description_value", + enabled=True, + etag="etag_value", + ) + ) + response = await client.get_guardrail(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.GetGuardrailRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, guardrail.Guardrail) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.enabled is True + assert response.etag == "etag_value" + + +@pytest.mark.asyncio +async def test_get_guardrail_async_from_dict(): + await test_get_guardrail_async(request_type=dict) + + +def test_get_guardrail_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.GetGuardrailRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_guardrail), "__call__") as call: + call.return_value = guardrail.Guardrail() + client.get_guardrail(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_guardrail_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.GetGuardrailRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_guardrail), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(guardrail.Guardrail()) + await client.get_guardrail(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_guardrail_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_guardrail), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = guardrail.Guardrail() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_guardrail( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_guardrail_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_guardrail( + agent_service.GetGuardrailRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_guardrail_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_guardrail), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = guardrail.Guardrail() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(guardrail.Guardrail()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_guardrail( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_guardrail_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_guardrail( + agent_service.GetGuardrailRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.CreateGuardrailRequest, + dict, + ], +) +def test_create_guardrail(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_guardrail), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_guardrail.Guardrail( + name="name_value", + display_name="display_name_value", + description="description_value", + enabled=True, + etag="etag_value", + ) + response = client.create_guardrail(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.CreateGuardrailRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_guardrail.Guardrail) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.enabled is True + assert response.etag == "etag_value" + + +def test_create_guardrail_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.CreateGuardrailRequest( + parent="parent_value", + guardrail_id="guardrail_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_guardrail), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_guardrail(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.CreateGuardrailRequest( + parent="parent_value", + guardrail_id="guardrail_id_value", + ) + + +def test_create_guardrail_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_guardrail in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_guardrail] = ( + mock_rpc + ) + request = {} + client.create_guardrail(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_guardrail(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_guardrail_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_guardrail + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_guardrail + ] = mock_rpc + + request = {} + await client.create_guardrail(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_guardrail(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_guardrail_async( + transport: str = "grpc_asyncio", request_type=agent_service.CreateGuardrailRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_guardrail), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_guardrail.Guardrail( + name="name_value", + display_name="display_name_value", + description="description_value", + enabled=True, + etag="etag_value", + ) + ) + response = await client.create_guardrail(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.CreateGuardrailRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_guardrail.Guardrail) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.enabled is True + assert response.etag == "etag_value" + + +@pytest.mark.asyncio +async def test_create_guardrail_async_from_dict(): + await test_create_guardrail_async(request_type=dict) + + +def test_create_guardrail_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.CreateGuardrailRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_guardrail), "__call__") as call: + call.return_value = gcc_guardrail.Guardrail() + client.create_guardrail(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_guardrail_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.CreateGuardrailRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_guardrail), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_guardrail.Guardrail() + ) + await client.create_guardrail(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_guardrail_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_guardrail), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_guardrail.Guardrail() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_guardrail( + parent="parent_value", + guardrail=gcc_guardrail.Guardrail( + content_filter=gcc_guardrail.Guardrail.ContentFilter( + banned_contents=["banned_contents_value"] + ) + ), + guardrail_id="guardrail_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].guardrail + mock_val = gcc_guardrail.Guardrail( + content_filter=gcc_guardrail.Guardrail.ContentFilter( + banned_contents=["banned_contents_value"] + ) + ) + assert arg == mock_val + arg = args[0].guardrail_id + mock_val = "guardrail_id_value" + assert arg == mock_val + + +def test_create_guardrail_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_guardrail( + agent_service.CreateGuardrailRequest(), + parent="parent_value", + guardrail=gcc_guardrail.Guardrail( + content_filter=gcc_guardrail.Guardrail.ContentFilter( + banned_contents=["banned_contents_value"] + ) + ), + guardrail_id="guardrail_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_guardrail_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_guardrail), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_guardrail.Guardrail() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_guardrail.Guardrail() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_guardrail( + parent="parent_value", + guardrail=gcc_guardrail.Guardrail( + content_filter=gcc_guardrail.Guardrail.ContentFilter( + banned_contents=["banned_contents_value"] + ) + ), + guardrail_id="guardrail_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].guardrail + mock_val = gcc_guardrail.Guardrail( + content_filter=gcc_guardrail.Guardrail.ContentFilter( + banned_contents=["banned_contents_value"] + ) + ) + assert arg == mock_val + arg = args[0].guardrail_id + mock_val = "guardrail_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_guardrail_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_guardrail( + agent_service.CreateGuardrailRequest(), + parent="parent_value", + guardrail=gcc_guardrail.Guardrail( + content_filter=gcc_guardrail.Guardrail.ContentFilter( + banned_contents=["banned_contents_value"] + ) + ), + guardrail_id="guardrail_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.UpdateGuardrailRequest, + dict, + ], +) +def test_update_guardrail(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_guardrail), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_guardrail.Guardrail( + name="name_value", + display_name="display_name_value", + description="description_value", + enabled=True, + etag="etag_value", + ) + response = client.update_guardrail(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.UpdateGuardrailRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_guardrail.Guardrail) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.enabled is True + assert response.etag == "etag_value" + + +def test_update_guardrail_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.UpdateGuardrailRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_guardrail), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_guardrail(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.UpdateGuardrailRequest() + + +def test_update_guardrail_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_guardrail in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_guardrail] = ( + mock_rpc + ) + request = {} + client.update_guardrail(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_guardrail(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_guardrail_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_guardrail + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_guardrail + ] = mock_rpc + + request = {} + await client.update_guardrail(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_guardrail(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_guardrail_async( + transport: str = "grpc_asyncio", request_type=agent_service.UpdateGuardrailRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_guardrail), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_guardrail.Guardrail( + name="name_value", + display_name="display_name_value", + description="description_value", + enabled=True, + etag="etag_value", + ) + ) + response = await client.update_guardrail(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.UpdateGuardrailRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_guardrail.Guardrail) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.enabled is True + assert response.etag == "etag_value" + + +@pytest.mark.asyncio +async def test_update_guardrail_async_from_dict(): + await test_update_guardrail_async(request_type=dict) + + +def test_update_guardrail_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.UpdateGuardrailRequest() + + request.guardrail.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_guardrail), "__call__") as call: + call.return_value = gcc_guardrail.Guardrail() + client.update_guardrail(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "guardrail.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_guardrail_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.UpdateGuardrailRequest() + + request.guardrail.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_guardrail), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_guardrail.Guardrail() + ) + await client.update_guardrail(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "guardrail.name=name_value", + ) in kw["metadata"] + + +def test_update_guardrail_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_guardrail), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_guardrail.Guardrail() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_guardrail( + guardrail=gcc_guardrail.Guardrail( + content_filter=gcc_guardrail.Guardrail.ContentFilter( + banned_contents=["banned_contents_value"] + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].guardrail + mock_val = gcc_guardrail.Guardrail( + content_filter=gcc_guardrail.Guardrail.ContentFilter( + banned_contents=["banned_contents_value"] + ) + ) + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_guardrail_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_guardrail( + agent_service.UpdateGuardrailRequest(), + guardrail=gcc_guardrail.Guardrail( + content_filter=gcc_guardrail.Guardrail.ContentFilter( + banned_contents=["banned_contents_value"] + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_guardrail_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_guardrail), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_guardrail.Guardrail() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_guardrail.Guardrail() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_guardrail( + guardrail=gcc_guardrail.Guardrail( + content_filter=gcc_guardrail.Guardrail.ContentFilter( + banned_contents=["banned_contents_value"] + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].guardrail + mock_val = gcc_guardrail.Guardrail( + content_filter=gcc_guardrail.Guardrail.ContentFilter( + banned_contents=["banned_contents_value"] + ) + ) + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_guardrail_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_guardrail( + agent_service.UpdateGuardrailRequest(), + guardrail=gcc_guardrail.Guardrail( + content_filter=gcc_guardrail.Guardrail.ContentFilter( + banned_contents=["banned_contents_value"] + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.DeleteGuardrailRequest, + dict, + ], +) +def test_delete_guardrail(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_guardrail), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_guardrail(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.DeleteGuardrailRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_guardrail_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.DeleteGuardrailRequest( + name="name_value", + etag="etag_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_guardrail), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_guardrail(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.DeleteGuardrailRequest( + name="name_value", + etag="etag_value", + ) + + +def test_delete_guardrail_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_guardrail in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_guardrail] = ( + mock_rpc + ) + request = {} + client.delete_guardrail(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_guardrail(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_guardrail_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_guardrail + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_guardrail + ] = mock_rpc + + request = {} + await client.delete_guardrail(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_guardrail(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_guardrail_async( + transport: str = "grpc_asyncio", request_type=agent_service.DeleteGuardrailRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_guardrail), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_guardrail(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.DeleteGuardrailRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_guardrail_async_from_dict(): + await test_delete_guardrail_async(request_type=dict) + + +def test_delete_guardrail_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.DeleteGuardrailRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_guardrail), "__call__") as call: + call.return_value = None + client.delete_guardrail(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_guardrail_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.DeleteGuardrailRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_guardrail), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_guardrail(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_guardrail_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_guardrail), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_guardrail( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_guardrail_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_guardrail( + agent_service.DeleteGuardrailRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_guardrail_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_guardrail), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_guardrail( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_guardrail_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_guardrail( + agent_service.DeleteGuardrailRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.ListDeploymentsRequest, + dict, + ], +) +def test_list_deployments(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_deployments), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = agent_service.ListDeploymentsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_deployments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.ListDeploymentsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDeploymentsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_deployments_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.ListDeploymentsRequest( + parent="parent_value", + page_token="page_token_value", + order_by="order_by_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_deployments), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_deployments(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.ListDeploymentsRequest( + parent="parent_value", + page_token="page_token_value", + order_by="order_by_value", + ) + + +def test_list_deployments_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_deployments in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_deployments] = ( + mock_rpc + ) + request = {} + client.list_deployments(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_deployments(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_deployments_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_deployments + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_deployments + ] = mock_rpc + + request = {} + await client.list_deployments(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_deployments(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_deployments_async( + transport: str = "grpc_asyncio", request_type=agent_service.ListDeploymentsRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_deployments), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent_service.ListDeploymentsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_deployments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.ListDeploymentsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDeploymentsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_deployments_async_from_dict(): + await test_list_deployments_async(request_type=dict) + + +def test_list_deployments_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.ListDeploymentsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_deployments), "__call__") as call: + call.return_value = agent_service.ListDeploymentsResponse() + client.list_deployments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_deployments_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.ListDeploymentsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_deployments), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent_service.ListDeploymentsResponse() + ) + await client.list_deployments(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_deployments_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_deployments), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = agent_service.ListDeploymentsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_deployments( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_deployments_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_deployments( + agent_service.ListDeploymentsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_deployments_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_deployments), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = agent_service.ListDeploymentsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent_service.ListDeploymentsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_deployments( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_deployments_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_deployments( + agent_service.ListDeploymentsRequest(), + parent="parent_value", + ) + + +def test_list_deployments_pager(transport_name: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_deployments), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + agent_service.ListDeploymentsResponse( + deployments=[ + deployment.Deployment(), + deployment.Deployment(), + deployment.Deployment(), + ], + next_page_token="abc", + ), + agent_service.ListDeploymentsResponse( + deployments=[], + next_page_token="def", + ), + agent_service.ListDeploymentsResponse( + deployments=[ + deployment.Deployment(), + ], + next_page_token="ghi", + ), + agent_service.ListDeploymentsResponse( + deployments=[ + deployment.Deployment(), + deployment.Deployment(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_deployments(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, deployment.Deployment) for i in results) + + +def test_list_deployments_pages(transport_name: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_deployments), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + agent_service.ListDeploymentsResponse( + deployments=[ + deployment.Deployment(), + deployment.Deployment(), + deployment.Deployment(), + ], + next_page_token="abc", + ), + agent_service.ListDeploymentsResponse( + deployments=[], + next_page_token="def", + ), + agent_service.ListDeploymentsResponse( + deployments=[ + deployment.Deployment(), + ], + next_page_token="ghi", + ), + agent_service.ListDeploymentsResponse( + deployments=[ + deployment.Deployment(), + deployment.Deployment(), + ], + ), + RuntimeError, + ) + pages = list(client.list_deployments(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_deployments_async_pager(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_deployments), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + agent_service.ListDeploymentsResponse( + deployments=[ + deployment.Deployment(), + deployment.Deployment(), + deployment.Deployment(), + ], + next_page_token="abc", + ), + agent_service.ListDeploymentsResponse( + deployments=[], + next_page_token="def", + ), + agent_service.ListDeploymentsResponse( + deployments=[ + deployment.Deployment(), + ], + next_page_token="ghi", + ), + agent_service.ListDeploymentsResponse( + deployments=[ + deployment.Deployment(), + deployment.Deployment(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_deployments( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, deployment.Deployment) for i in responses) + + +@pytest.mark.asyncio +async def test_list_deployments_async_pages(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_deployments), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + agent_service.ListDeploymentsResponse( + deployments=[ + deployment.Deployment(), + deployment.Deployment(), + deployment.Deployment(), + ], + next_page_token="abc", + ), + agent_service.ListDeploymentsResponse( + deployments=[], + next_page_token="def", + ), + agent_service.ListDeploymentsResponse( + deployments=[ + deployment.Deployment(), + ], + next_page_token="ghi", + ), + agent_service.ListDeploymentsResponse( + deployments=[ + deployment.Deployment(), + deployment.Deployment(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_deployments(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.GetDeploymentRequest, + dict, + ], +) +def test_get_deployment(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_deployment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = deployment.Deployment( + name="name_value", + display_name="display_name_value", + app_version="app_version_value", + etag="etag_value", + ) + response = client.get_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.GetDeploymentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, deployment.Deployment) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.app_version == "app_version_value" + assert response.etag == "etag_value" + + +def test_get_deployment_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.GetDeploymentRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_deployment), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_deployment(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.GetDeploymentRequest( + name="name_value", + ) + + +def test_get_deployment_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_deployment in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_deployment] = mock_rpc + request = {} + client.get_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_deployment(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_deployment_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_deployment + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_deployment + ] = mock_rpc + + request = {} + await client.get_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_deployment(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_deployment_async( + transport: str = "grpc_asyncio", request_type=agent_service.GetDeploymentRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_deployment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + deployment.Deployment( + name="name_value", + display_name="display_name_value", + app_version="app_version_value", + etag="etag_value", + ) + ) + response = await client.get_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.GetDeploymentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, deployment.Deployment) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.app_version == "app_version_value" + assert response.etag == "etag_value" + + +@pytest.mark.asyncio +async def test_get_deployment_async_from_dict(): + await test_get_deployment_async(request_type=dict) + + +def test_get_deployment_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.GetDeploymentRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_deployment), "__call__") as call: + call.return_value = deployment.Deployment() + client.get_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_deployment_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.GetDeploymentRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_deployment), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + deployment.Deployment() + ) + await client.get_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_deployment_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_deployment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = deployment.Deployment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_deployment( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_deployment_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_deployment( + agent_service.GetDeploymentRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_deployment_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_deployment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = deployment.Deployment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + deployment.Deployment() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_deployment( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_deployment_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_deployment( + agent_service.GetDeploymentRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.CreateDeploymentRequest, + dict, + ], +) +def test_create_deployment(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_deployment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_deployment.Deployment( + name="name_value", + display_name="display_name_value", + app_version="app_version_value", + etag="etag_value", + ) + response = client.create_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.CreateDeploymentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_deployment.Deployment) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.app_version == "app_version_value" + assert response.etag == "etag_value" + + +def test_create_deployment_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.CreateDeploymentRequest( + parent="parent_value", + deployment_id="deployment_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_deployment), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_deployment(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.CreateDeploymentRequest( + parent="parent_value", + deployment_id="deployment_id_value", + ) + + +def test_create_deployment_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_deployment in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_deployment] = ( + mock_rpc + ) + request = {} + client.create_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_deployment(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_deployment_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_deployment + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_deployment + ] = mock_rpc + + request = {} + await client.create_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_deployment(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_deployment_async( + transport: str = "grpc_asyncio", request_type=agent_service.CreateDeploymentRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_deployment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_deployment.Deployment( + name="name_value", + display_name="display_name_value", + app_version="app_version_value", + etag="etag_value", + ) + ) + response = await client.create_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.CreateDeploymentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_deployment.Deployment) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.app_version == "app_version_value" + assert response.etag == "etag_value" + + +@pytest.mark.asyncio +async def test_create_deployment_async_from_dict(): + await test_create_deployment_async(request_type=dict) + + +def test_create_deployment_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.CreateDeploymentRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_deployment), "__call__" + ) as call: + call.return_value = gcc_deployment.Deployment() + client.create_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_deployment_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.CreateDeploymentRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_deployment), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_deployment.Deployment() + ) + await client.create_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_deployment_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_deployment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_deployment.Deployment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_deployment( + parent="parent_value", + deployment=gcc_deployment.Deployment(name="name_value"), + deployment_id="deployment_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].deployment + mock_val = gcc_deployment.Deployment(name="name_value") + assert arg == mock_val + arg = args[0].deployment_id + mock_val = "deployment_id_value" + assert arg == mock_val + + +def test_create_deployment_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_deployment( + agent_service.CreateDeploymentRequest(), + parent="parent_value", + deployment=gcc_deployment.Deployment(name="name_value"), + deployment_id="deployment_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_deployment_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_deployment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_deployment.Deployment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_deployment.Deployment() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_deployment( + parent="parent_value", + deployment=gcc_deployment.Deployment(name="name_value"), + deployment_id="deployment_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].deployment + mock_val = gcc_deployment.Deployment(name="name_value") + assert arg == mock_val + arg = args[0].deployment_id + mock_val = "deployment_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_deployment_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_deployment( + agent_service.CreateDeploymentRequest(), + parent="parent_value", + deployment=gcc_deployment.Deployment(name="name_value"), + deployment_id="deployment_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.UpdateDeploymentRequest, + dict, + ], +) +def test_update_deployment(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_deployment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_deployment.Deployment( + name="name_value", + display_name="display_name_value", + app_version="app_version_value", + etag="etag_value", + ) + response = client.update_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.UpdateDeploymentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_deployment.Deployment) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.app_version == "app_version_value" + assert response.etag == "etag_value" + + +def test_update_deployment_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.UpdateDeploymentRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_deployment), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_deployment(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.UpdateDeploymentRequest() + + +def test_update_deployment_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_deployment in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_deployment] = ( + mock_rpc + ) + request = {} + client.update_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_deployment(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_deployment_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_deployment + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_deployment + ] = mock_rpc + + request = {} + await client.update_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_deployment(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_deployment_async( + transport: str = "grpc_asyncio", request_type=agent_service.UpdateDeploymentRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_deployment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_deployment.Deployment( + name="name_value", + display_name="display_name_value", + app_version="app_version_value", + etag="etag_value", + ) + ) + response = await client.update_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.UpdateDeploymentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_deployment.Deployment) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.app_version == "app_version_value" + assert response.etag == "etag_value" + + +@pytest.mark.asyncio +async def test_update_deployment_async_from_dict(): + await test_update_deployment_async(request_type=dict) + + +def test_update_deployment_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.UpdateDeploymentRequest() + + request.deployment.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_deployment), "__call__" + ) as call: + call.return_value = gcc_deployment.Deployment() + client.update_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "deployment.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_deployment_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.UpdateDeploymentRequest() + + request.deployment.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_deployment), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_deployment.Deployment() + ) + await client.update_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "deployment.name=name_value", + ) in kw["metadata"] + + +def test_update_deployment_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_deployment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_deployment.Deployment() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_deployment( + deployment=gcc_deployment.Deployment(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].deployment + mock_val = gcc_deployment.Deployment(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_deployment_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_deployment( + agent_service.UpdateDeploymentRequest(), + deployment=gcc_deployment.Deployment(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_deployment_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_deployment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_deployment.Deployment() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_deployment.Deployment() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_deployment( + deployment=gcc_deployment.Deployment(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].deployment + mock_val = gcc_deployment.Deployment(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_deployment_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_deployment( + agent_service.UpdateDeploymentRequest(), + deployment=gcc_deployment.Deployment(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.DeleteDeploymentRequest, + dict, + ], +) +def test_delete_deployment(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_deployment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.DeleteDeploymentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_deployment_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.DeleteDeploymentRequest( + name="name_value", + etag="etag_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_deployment), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_deployment(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.DeleteDeploymentRequest( + name="name_value", + etag="etag_value", + ) + + +def test_delete_deployment_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_deployment in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_deployment] = ( + mock_rpc + ) + request = {} + client.delete_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_deployment(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_deployment_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_deployment + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_deployment + ] = mock_rpc + + request = {} + await client.delete_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_deployment(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_deployment_async( + transport: str = "grpc_asyncio", request_type=agent_service.DeleteDeploymentRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_deployment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.DeleteDeploymentRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_deployment_async_from_dict(): + await test_delete_deployment_async(request_type=dict) + + +def test_delete_deployment_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.DeleteDeploymentRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_deployment), "__call__" + ) as call: + call.return_value = None + client.delete_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_deployment_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.DeleteDeploymentRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_deployment), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_deployment_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_deployment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_deployment( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_deployment_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_deployment( + agent_service.DeleteDeploymentRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_deployment_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_deployment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_deployment( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_deployment_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_deployment( + agent_service.DeleteDeploymentRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.ListToolsetsRequest, + dict, + ], +) +def test_list_toolsets(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_toolsets), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = agent_service.ListToolsetsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_toolsets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.ListToolsetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListToolsetsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_toolsets_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.ListToolsetsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_toolsets), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_toolsets(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.ListToolsetsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + +def test_list_toolsets_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_toolsets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_toolsets] = mock_rpc + request = {} + client.list_toolsets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_toolsets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_toolsets_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_toolsets + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_toolsets + ] = mock_rpc + + request = {} + await client.list_toolsets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_toolsets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_toolsets_async( + transport: str = "grpc_asyncio", request_type=agent_service.ListToolsetsRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_toolsets), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent_service.ListToolsetsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_toolsets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.ListToolsetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListToolsetsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_toolsets_async_from_dict(): + await test_list_toolsets_async(request_type=dict) + + +def test_list_toolsets_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.ListToolsetsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_toolsets), "__call__") as call: + call.return_value = agent_service.ListToolsetsResponse() + client.list_toolsets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_toolsets_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.ListToolsetsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_toolsets), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent_service.ListToolsetsResponse() + ) + await client.list_toolsets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_toolsets_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_toolsets), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = agent_service.ListToolsetsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_toolsets( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_toolsets_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_toolsets( + agent_service.ListToolsetsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_toolsets_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_toolsets), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = agent_service.ListToolsetsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent_service.ListToolsetsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_toolsets( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_toolsets_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_toolsets( + agent_service.ListToolsetsRequest(), + parent="parent_value", + ) + + +def test_list_toolsets_pager(transport_name: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_toolsets), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + agent_service.ListToolsetsResponse( + toolsets=[ + toolset.Toolset(), + toolset.Toolset(), + toolset.Toolset(), + ], + next_page_token="abc", + ), + agent_service.ListToolsetsResponse( + toolsets=[], + next_page_token="def", + ), + agent_service.ListToolsetsResponse( + toolsets=[ + toolset.Toolset(), + ], + next_page_token="ghi", + ), + agent_service.ListToolsetsResponse( + toolsets=[ + toolset.Toolset(), + toolset.Toolset(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_toolsets(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, toolset.Toolset) for i in results) + + +def test_list_toolsets_pages(transport_name: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_toolsets), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + agent_service.ListToolsetsResponse( + toolsets=[ + toolset.Toolset(), + toolset.Toolset(), + toolset.Toolset(), + ], + next_page_token="abc", + ), + agent_service.ListToolsetsResponse( + toolsets=[], + next_page_token="def", + ), + agent_service.ListToolsetsResponse( + toolsets=[ + toolset.Toolset(), + ], + next_page_token="ghi", + ), + agent_service.ListToolsetsResponse( + toolsets=[ + toolset.Toolset(), + toolset.Toolset(), + ], + ), + RuntimeError, + ) + pages = list(client.list_toolsets(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_toolsets_async_pager(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_toolsets), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + agent_service.ListToolsetsResponse( + toolsets=[ + toolset.Toolset(), + toolset.Toolset(), + toolset.Toolset(), + ], + next_page_token="abc", + ), + agent_service.ListToolsetsResponse( + toolsets=[], + next_page_token="def", + ), + agent_service.ListToolsetsResponse( + toolsets=[ + toolset.Toolset(), + ], + next_page_token="ghi", + ), + agent_service.ListToolsetsResponse( + toolsets=[ + toolset.Toolset(), + toolset.Toolset(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_toolsets( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, toolset.Toolset) for i in responses) + + +@pytest.mark.asyncio +async def test_list_toolsets_async_pages(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_toolsets), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + agent_service.ListToolsetsResponse( + toolsets=[ + toolset.Toolset(), + toolset.Toolset(), + toolset.Toolset(), + ], + next_page_token="abc", + ), + agent_service.ListToolsetsResponse( + toolsets=[], + next_page_token="def", + ), + agent_service.ListToolsetsResponse( + toolsets=[ + toolset.Toolset(), + ], + next_page_token="ghi", + ), + agent_service.ListToolsetsResponse( + toolsets=[ + toolset.Toolset(), + toolset.Toolset(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_toolsets(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.GetToolsetRequest, + dict, + ], +) +def test_get_toolset(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_toolset), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = toolset.Toolset( + name="name_value", + display_name="display_name_value", + description="description_value", + etag="etag_value", + execution_type=common.ExecutionType.SYNCHRONOUS, + ) + response = client.get_toolset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.GetToolsetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, toolset.Toolset) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.etag == "etag_value" + assert response.execution_type == common.ExecutionType.SYNCHRONOUS + + +def test_get_toolset_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.GetToolsetRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_toolset), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_toolset(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.GetToolsetRequest( + name="name_value", + ) + + +def test_get_toolset_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_toolset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_toolset] = mock_rpc + request = {} + client.get_toolset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_toolset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_toolset_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_toolset + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_toolset + ] = mock_rpc + + request = {} + await client.get_toolset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_toolset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_toolset_async( + transport: str = "grpc_asyncio", request_type=agent_service.GetToolsetRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_toolset), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + toolset.Toolset( + name="name_value", + display_name="display_name_value", + description="description_value", + etag="etag_value", + execution_type=common.ExecutionType.SYNCHRONOUS, + ) + ) + response = await client.get_toolset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.GetToolsetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, toolset.Toolset) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.etag == "etag_value" + assert response.execution_type == common.ExecutionType.SYNCHRONOUS + + +@pytest.mark.asyncio +async def test_get_toolset_async_from_dict(): + await test_get_toolset_async(request_type=dict) + + +def test_get_toolset_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.GetToolsetRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_toolset), "__call__") as call: + call.return_value = toolset.Toolset() + client.get_toolset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_toolset_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.GetToolsetRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_toolset), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(toolset.Toolset()) + await client.get_toolset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_toolset_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_toolset), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = toolset.Toolset() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_toolset( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_toolset_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_toolset( + agent_service.GetToolsetRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_toolset_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_toolset), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = toolset.Toolset() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(toolset.Toolset()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_toolset( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_toolset_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_toolset( + agent_service.GetToolsetRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.CreateToolsetRequest, + dict, + ], +) +def test_create_toolset(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_toolset), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_toolset.Toolset( + name="name_value", + display_name="display_name_value", + description="description_value", + etag="etag_value", + execution_type=common.ExecutionType.SYNCHRONOUS, + ) + response = client.create_toolset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.CreateToolsetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_toolset.Toolset) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.etag == "etag_value" + assert response.execution_type == common.ExecutionType.SYNCHRONOUS + + +def test_create_toolset_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.CreateToolsetRequest( + parent="parent_value", + toolset_id="toolset_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_toolset), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_toolset(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.CreateToolsetRequest( + parent="parent_value", + toolset_id="toolset_id_value", + ) + + +def test_create_toolset_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_toolset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_toolset] = mock_rpc + request = {} + client.create_toolset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_toolset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_toolset_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_toolset + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_toolset + ] = mock_rpc + + request = {} + await client.create_toolset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_toolset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_toolset_async( + transport: str = "grpc_asyncio", request_type=agent_service.CreateToolsetRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_toolset), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_toolset.Toolset( + name="name_value", + display_name="display_name_value", + description="description_value", + etag="etag_value", + execution_type=common.ExecutionType.SYNCHRONOUS, + ) + ) + response = await client.create_toolset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.CreateToolsetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_toolset.Toolset) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.etag == "etag_value" + assert response.execution_type == common.ExecutionType.SYNCHRONOUS + + +@pytest.mark.asyncio +async def test_create_toolset_async_from_dict(): + await test_create_toolset_async(request_type=dict) + + +def test_create_toolset_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.CreateToolsetRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_toolset), "__call__") as call: + call.return_value = gcc_toolset.Toolset() + client.create_toolset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_toolset_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.CreateToolsetRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_toolset), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcc_toolset.Toolset()) + await client.create_toolset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_toolset_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_toolset), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_toolset.Toolset() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_toolset( + parent="parent_value", + toolset=gcc_toolset.Toolset( + mcp_toolset=mcp_toolset.McpToolset( + server_address="server_address_value" + ) + ), + toolset_id="toolset_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].toolset + mock_val = gcc_toolset.Toolset( + mcp_toolset=mcp_toolset.McpToolset(server_address="server_address_value") + ) + assert arg == mock_val + arg = args[0].toolset_id + mock_val = "toolset_id_value" + assert arg == mock_val + + +def test_create_toolset_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_toolset( + agent_service.CreateToolsetRequest(), + parent="parent_value", + toolset=gcc_toolset.Toolset( + mcp_toolset=mcp_toolset.McpToolset( + server_address="server_address_value" + ) + ), + toolset_id="toolset_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_toolset_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_toolset), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_toolset.Toolset() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcc_toolset.Toolset()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_toolset( + parent="parent_value", + toolset=gcc_toolset.Toolset( + mcp_toolset=mcp_toolset.McpToolset( + server_address="server_address_value" + ) + ), + toolset_id="toolset_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].toolset + mock_val = gcc_toolset.Toolset( + mcp_toolset=mcp_toolset.McpToolset(server_address="server_address_value") + ) + assert arg == mock_val + arg = args[0].toolset_id + mock_val = "toolset_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_toolset_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_toolset( + agent_service.CreateToolsetRequest(), + parent="parent_value", + toolset=gcc_toolset.Toolset( + mcp_toolset=mcp_toolset.McpToolset( + server_address="server_address_value" + ) + ), + toolset_id="toolset_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.UpdateToolsetRequest, + dict, + ], +) +def test_update_toolset(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_toolset), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_toolset.Toolset( + name="name_value", + display_name="display_name_value", + description="description_value", + etag="etag_value", + execution_type=common.ExecutionType.SYNCHRONOUS, + ) + response = client.update_toolset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.UpdateToolsetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_toolset.Toolset) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.etag == "etag_value" + assert response.execution_type == common.ExecutionType.SYNCHRONOUS + + +def test_update_toolset_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.UpdateToolsetRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_toolset), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_toolset(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.UpdateToolsetRequest() + + +def test_update_toolset_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_toolset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_toolset] = mock_rpc + request = {} + client.update_toolset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_toolset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_toolset_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_toolset + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_toolset + ] = mock_rpc + + request = {} + await client.update_toolset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_toolset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_toolset_async( + transport: str = "grpc_asyncio", request_type=agent_service.UpdateToolsetRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_toolset), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_toolset.Toolset( + name="name_value", + display_name="display_name_value", + description="description_value", + etag="etag_value", + execution_type=common.ExecutionType.SYNCHRONOUS, + ) + ) + response = await client.update_toolset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.UpdateToolsetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_toolset.Toolset) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.etag == "etag_value" + assert response.execution_type == common.ExecutionType.SYNCHRONOUS + + +@pytest.mark.asyncio +async def test_update_toolset_async_from_dict(): + await test_update_toolset_async(request_type=dict) + + +def test_update_toolset_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.UpdateToolsetRequest() + + request.toolset.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_toolset), "__call__") as call: + call.return_value = gcc_toolset.Toolset() + client.update_toolset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "toolset.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_toolset_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.UpdateToolsetRequest() + + request.toolset.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_toolset), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcc_toolset.Toolset()) + await client.update_toolset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "toolset.name=name_value", + ) in kw["metadata"] + + +def test_update_toolset_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_toolset), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_toolset.Toolset() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_toolset( + toolset=gcc_toolset.Toolset( + mcp_toolset=mcp_toolset.McpToolset( + server_address="server_address_value" + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].toolset + mock_val = gcc_toolset.Toolset( + mcp_toolset=mcp_toolset.McpToolset(server_address="server_address_value") + ) + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_toolset_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_toolset( + agent_service.UpdateToolsetRequest(), + toolset=gcc_toolset.Toolset( + mcp_toolset=mcp_toolset.McpToolset( + server_address="server_address_value" + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_toolset_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_toolset), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_toolset.Toolset() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcc_toolset.Toolset()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_toolset( + toolset=gcc_toolset.Toolset( + mcp_toolset=mcp_toolset.McpToolset( + server_address="server_address_value" + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].toolset + mock_val = gcc_toolset.Toolset( + mcp_toolset=mcp_toolset.McpToolset(server_address="server_address_value") + ) + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_toolset_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_toolset( + agent_service.UpdateToolsetRequest(), + toolset=gcc_toolset.Toolset( + mcp_toolset=mcp_toolset.McpToolset( + server_address="server_address_value" + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.DeleteToolsetRequest, + dict, + ], +) +def test_delete_toolset(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_toolset), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_toolset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.DeleteToolsetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_toolset_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.DeleteToolsetRequest( + name="name_value", + etag="etag_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_toolset), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_toolset(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.DeleteToolsetRequest( + name="name_value", + etag="etag_value", + ) + + +def test_delete_toolset_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_toolset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_toolset] = mock_rpc + request = {} + client.delete_toolset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_toolset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_toolset_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_toolset + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_toolset + ] = mock_rpc + + request = {} + await client.delete_toolset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_toolset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_toolset_async( + transport: str = "grpc_asyncio", request_type=agent_service.DeleteToolsetRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_toolset), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_toolset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.DeleteToolsetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_toolset_async_from_dict(): + await test_delete_toolset_async(request_type=dict) + + +def test_delete_toolset_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.DeleteToolsetRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_toolset), "__call__") as call: + call.return_value = None + client.delete_toolset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_toolset_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.DeleteToolsetRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_toolset), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_toolset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_toolset_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_toolset), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_toolset( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_toolset_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_toolset( + agent_service.DeleteToolsetRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_toolset_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_toolset), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_toolset( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_toolset_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_toolset( + agent_service.DeleteToolsetRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.ListAppVersionsRequest, + dict, + ], +) +def test_list_app_versions(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_app_versions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = agent_service.ListAppVersionsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_app_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.ListAppVersionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAppVersionsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_app_versions_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.ListAppVersionsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_app_versions), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_app_versions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.ListAppVersionsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + +def test_list_app_versions_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_app_versions in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_app_versions] = ( + mock_rpc + ) + request = {} + client.list_app_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_app_versions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_app_versions_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_app_versions + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_app_versions + ] = mock_rpc + + request = {} + await client.list_app_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_app_versions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_app_versions_async( + transport: str = "grpc_asyncio", request_type=agent_service.ListAppVersionsRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_app_versions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent_service.ListAppVersionsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_app_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.ListAppVersionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAppVersionsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_app_versions_async_from_dict(): + await test_list_app_versions_async(request_type=dict) + + +def test_list_app_versions_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.ListAppVersionsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_app_versions), "__call__" + ) as call: + call.return_value = agent_service.ListAppVersionsResponse() + client.list_app_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_app_versions_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.ListAppVersionsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_app_versions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent_service.ListAppVersionsResponse() + ) + await client.list_app_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_app_versions_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_app_versions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = agent_service.ListAppVersionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_app_versions( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_app_versions_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_app_versions( + agent_service.ListAppVersionsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_app_versions_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_app_versions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = agent_service.ListAppVersionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent_service.ListAppVersionsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_app_versions( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_app_versions_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_app_versions( + agent_service.ListAppVersionsRequest(), + parent="parent_value", + ) + + +def test_list_app_versions_pager(transport_name: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_app_versions), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + agent_service.ListAppVersionsResponse( + app_versions=[ + app_version.AppVersion(), + app_version.AppVersion(), + app_version.AppVersion(), + ], + next_page_token="abc", + ), + agent_service.ListAppVersionsResponse( + app_versions=[], + next_page_token="def", + ), + agent_service.ListAppVersionsResponse( + app_versions=[ + app_version.AppVersion(), + ], + next_page_token="ghi", + ), + agent_service.ListAppVersionsResponse( + app_versions=[ + app_version.AppVersion(), + app_version.AppVersion(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_app_versions(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, app_version.AppVersion) for i in results) + + +def test_list_app_versions_pages(transport_name: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_app_versions), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + agent_service.ListAppVersionsResponse( + app_versions=[ + app_version.AppVersion(), + app_version.AppVersion(), + app_version.AppVersion(), + ], + next_page_token="abc", + ), + agent_service.ListAppVersionsResponse( + app_versions=[], + next_page_token="def", + ), + agent_service.ListAppVersionsResponse( + app_versions=[ + app_version.AppVersion(), + ], + next_page_token="ghi", + ), + agent_service.ListAppVersionsResponse( + app_versions=[ + app_version.AppVersion(), + app_version.AppVersion(), + ], + ), + RuntimeError, + ) + pages = list(client.list_app_versions(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_app_versions_async_pager(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_app_versions), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + agent_service.ListAppVersionsResponse( + app_versions=[ + app_version.AppVersion(), + app_version.AppVersion(), + app_version.AppVersion(), + ], + next_page_token="abc", + ), + agent_service.ListAppVersionsResponse( + app_versions=[], + next_page_token="def", + ), + agent_service.ListAppVersionsResponse( + app_versions=[ + app_version.AppVersion(), + ], + next_page_token="ghi", + ), + agent_service.ListAppVersionsResponse( + app_versions=[ + app_version.AppVersion(), + app_version.AppVersion(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_app_versions( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, app_version.AppVersion) for i in responses) + + +@pytest.mark.asyncio +async def test_list_app_versions_async_pages(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_app_versions), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + agent_service.ListAppVersionsResponse( + app_versions=[ + app_version.AppVersion(), + app_version.AppVersion(), + app_version.AppVersion(), + ], + next_page_token="abc", + ), + agent_service.ListAppVersionsResponse( + app_versions=[], + next_page_token="def", + ), + agent_service.ListAppVersionsResponse( + app_versions=[ + app_version.AppVersion(), + ], + next_page_token="ghi", + ), + agent_service.ListAppVersionsResponse( + app_versions=[ + app_version.AppVersion(), + app_version.AppVersion(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_app_versions(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.GetAppVersionRequest, + dict, + ], +) +def test_get_app_version(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_app_version), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = app_version.AppVersion( + name="name_value", + display_name="display_name_value", + description="description_value", + creator="creator_value", + etag="etag_value", + ) + response = client.get_app_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.GetAppVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, app_version.AppVersion) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.creator == "creator_value" + assert response.etag == "etag_value" + + +def test_get_app_version_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.GetAppVersionRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_app_version), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_app_version(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.GetAppVersionRequest( + name="name_value", + ) + + +def test_get_app_version_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_app_version in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_app_version] = mock_rpc + request = {} + client.get_app_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_app_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_app_version_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_app_version + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_app_version + ] = mock_rpc + + request = {} + await client.get_app_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_app_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_app_version_async( + transport: str = "grpc_asyncio", request_type=agent_service.GetAppVersionRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_app_version), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + app_version.AppVersion( + name="name_value", + display_name="display_name_value", + description="description_value", + creator="creator_value", + etag="etag_value", + ) + ) + response = await client.get_app_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.GetAppVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, app_version.AppVersion) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.creator == "creator_value" + assert response.etag == "etag_value" + + +@pytest.mark.asyncio +async def test_get_app_version_async_from_dict(): + await test_get_app_version_async(request_type=dict) + + +def test_get_app_version_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.GetAppVersionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_app_version), "__call__") as call: + call.return_value = app_version.AppVersion() + client.get_app_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_app_version_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.GetAppVersionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_app_version), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + app_version.AppVersion() + ) + await client.get_app_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_app_version_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_app_version), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = app_version.AppVersion() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_app_version( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_app_version_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_app_version( + agent_service.GetAppVersionRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_app_version_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_app_version), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = app_version.AppVersion() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + app_version.AppVersion() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_app_version( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_app_version_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_app_version( + agent_service.GetAppVersionRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.CreateAppVersionRequest, + dict, + ], +) +def test_create_app_version(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_app_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_app_version.AppVersion( + name="name_value", + display_name="display_name_value", + description="description_value", + creator="creator_value", + etag="etag_value", + ) + response = client.create_app_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.CreateAppVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_app_version.AppVersion) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.creator == "creator_value" + assert response.etag == "etag_value" + + +def test_create_app_version_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.CreateAppVersionRequest( + parent="parent_value", + app_version_id="app_version_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_app_version), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_app_version(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.CreateAppVersionRequest( + parent="parent_value", + app_version_id="app_version_id_value", + ) + + +def test_create_app_version_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_app_version in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_app_version] = ( + mock_rpc + ) + request = {} + client.create_app_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_app_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_app_version_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_app_version + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_app_version + ] = mock_rpc + + request = {} + await client.create_app_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_app_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_app_version_async( + transport: str = "grpc_asyncio", request_type=agent_service.CreateAppVersionRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_app_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_app_version.AppVersion( + name="name_value", + display_name="display_name_value", + description="description_value", + creator="creator_value", + etag="etag_value", + ) + ) + response = await client.create_app_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.CreateAppVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_app_version.AppVersion) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.creator == "creator_value" + assert response.etag == "etag_value" + + +@pytest.mark.asyncio +async def test_create_app_version_async_from_dict(): + await test_create_app_version_async(request_type=dict) + + +def test_create_app_version_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.CreateAppVersionRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_app_version), "__call__" + ) as call: + call.return_value = gcc_app_version.AppVersion() + client.create_app_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_app_version_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.CreateAppVersionRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_app_version), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_app_version.AppVersion() + ) + await client.create_app_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_app_version_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_app_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_app_version.AppVersion() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_app_version( + parent="parent_value", + app_version=gcc_app_version.AppVersion(name="name_value"), + app_version_id="app_version_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].app_version + mock_val = gcc_app_version.AppVersion(name="name_value") + assert arg == mock_val + arg = args[0].app_version_id + mock_val = "app_version_id_value" + assert arg == mock_val + + +def test_create_app_version_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_app_version( + agent_service.CreateAppVersionRequest(), + parent="parent_value", + app_version=gcc_app_version.AppVersion(name="name_value"), + app_version_id="app_version_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_app_version_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_app_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_app_version.AppVersion() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_app_version.AppVersion() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_app_version( + parent="parent_value", + app_version=gcc_app_version.AppVersion(name="name_value"), + app_version_id="app_version_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].app_version + mock_val = gcc_app_version.AppVersion(name="name_value") + assert arg == mock_val + arg = args[0].app_version_id + mock_val = "app_version_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_app_version_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_app_version( + agent_service.CreateAppVersionRequest(), + parent="parent_value", + app_version=gcc_app_version.AppVersion(name="name_value"), + app_version_id="app_version_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.DeleteAppVersionRequest, + dict, + ], +) +def test_delete_app_version(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_app_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_app_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.DeleteAppVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_app_version_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.DeleteAppVersionRequest( + name="name_value", + etag="etag_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_app_version), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_app_version(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.DeleteAppVersionRequest( + name="name_value", + etag="etag_value", + ) + + +def test_delete_app_version_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_app_version in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_app_version] = ( + mock_rpc + ) + request = {} + client.delete_app_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_app_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_app_version_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_app_version + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_app_version + ] = mock_rpc + + request = {} + await client.delete_app_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_app_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_app_version_async( + transport: str = "grpc_asyncio", request_type=agent_service.DeleteAppVersionRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_app_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_app_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.DeleteAppVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_app_version_async_from_dict(): + await test_delete_app_version_async(request_type=dict) + + +def test_delete_app_version_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.DeleteAppVersionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_app_version), "__call__" + ) as call: + call.return_value = None + client.delete_app_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_app_version_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.DeleteAppVersionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_app_version), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_app_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_app_version_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_app_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_app_version( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_app_version_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_app_version( + agent_service.DeleteAppVersionRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_app_version_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_app_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_app_version( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_app_version_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_app_version( + agent_service.DeleteAppVersionRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.RestoreAppVersionRequest, + dict, + ], +) +def test_restore_app_version(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_app_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.restore_app_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.RestoreAppVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_restore_app_version_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.RestoreAppVersionRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_app_version), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.restore_app_version(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.RestoreAppVersionRequest( + name="name_value", + ) + + +def test_restore_app_version_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.restore_app_version in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.restore_app_version] = ( + mock_rpc + ) + request = {} + client.restore_app_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.restore_app_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_restore_app_version_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.restore_app_version + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.restore_app_version + ] = mock_rpc + + request = {} + await client.restore_app_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.restore_app_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_restore_app_version_async( + transport: str = "grpc_asyncio", request_type=agent_service.RestoreAppVersionRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_app_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.restore_app_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.RestoreAppVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_restore_app_version_async_from_dict(): + await test_restore_app_version_async(request_type=dict) + + +def test_restore_app_version_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.RestoreAppVersionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_app_version), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.restore_app_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_restore_app_version_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.RestoreAppVersionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_app_version), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.restore_app_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_restore_app_version_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_app_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.restore_app_version( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_restore_app_version_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.restore_app_version( + agent_service.RestoreAppVersionRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_restore_app_version_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_app_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.restore_app_version( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_restore_app_version_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.restore_app_version( + agent_service.RestoreAppVersionRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.ListChangelogsRequest, + dict, + ], +) +def test_list_changelogs(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_changelogs), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = agent_service.ListChangelogsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_changelogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.ListChangelogsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListChangelogsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_changelogs_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.ListChangelogsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_changelogs), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_changelogs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.ListChangelogsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + +def test_list_changelogs_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_changelogs in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_changelogs] = mock_rpc + request = {} + client.list_changelogs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_changelogs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_changelogs_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_changelogs + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_changelogs + ] = mock_rpc + + request = {} + await client.list_changelogs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_changelogs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_changelogs_async( + transport: str = "grpc_asyncio", request_type=agent_service.ListChangelogsRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_changelogs), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent_service.ListChangelogsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_changelogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.ListChangelogsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListChangelogsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_changelogs_async_from_dict(): + await test_list_changelogs_async(request_type=dict) + + +def test_list_changelogs_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.ListChangelogsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_changelogs), "__call__") as call: + call.return_value = agent_service.ListChangelogsResponse() + client.list_changelogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_changelogs_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.ListChangelogsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_changelogs), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent_service.ListChangelogsResponse() + ) + await client.list_changelogs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_changelogs_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_changelogs), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = agent_service.ListChangelogsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_changelogs( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_changelogs_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_changelogs( + agent_service.ListChangelogsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_changelogs_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_changelogs), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = agent_service.ListChangelogsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent_service.ListChangelogsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_changelogs( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_changelogs_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_changelogs( + agent_service.ListChangelogsRequest(), + parent="parent_value", + ) + + +def test_list_changelogs_pager(transport_name: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_changelogs), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + agent_service.ListChangelogsResponse( + changelogs=[ + changelog.Changelog(), + changelog.Changelog(), + changelog.Changelog(), + ], + next_page_token="abc", + ), + agent_service.ListChangelogsResponse( + changelogs=[], + next_page_token="def", + ), + agent_service.ListChangelogsResponse( + changelogs=[ + changelog.Changelog(), + ], + next_page_token="ghi", + ), + agent_service.ListChangelogsResponse( + changelogs=[ + changelog.Changelog(), + changelog.Changelog(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_changelogs(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, changelog.Changelog) for i in results) + + +def test_list_changelogs_pages(transport_name: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_changelogs), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + agent_service.ListChangelogsResponse( + changelogs=[ + changelog.Changelog(), + changelog.Changelog(), + changelog.Changelog(), + ], + next_page_token="abc", + ), + agent_service.ListChangelogsResponse( + changelogs=[], + next_page_token="def", + ), + agent_service.ListChangelogsResponse( + changelogs=[ + changelog.Changelog(), + ], + next_page_token="ghi", + ), + agent_service.ListChangelogsResponse( + changelogs=[ + changelog.Changelog(), + changelog.Changelog(), + ], + ), + RuntimeError, + ) + pages = list(client.list_changelogs(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_changelogs_async_pager(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_changelogs), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + agent_service.ListChangelogsResponse( + changelogs=[ + changelog.Changelog(), + changelog.Changelog(), + changelog.Changelog(), + ], + next_page_token="abc", + ), + agent_service.ListChangelogsResponse( + changelogs=[], + next_page_token="def", + ), + agent_service.ListChangelogsResponse( + changelogs=[ + changelog.Changelog(), + ], + next_page_token="ghi", + ), + agent_service.ListChangelogsResponse( + changelogs=[ + changelog.Changelog(), + changelog.Changelog(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_changelogs( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, changelog.Changelog) for i in responses) + + +@pytest.mark.asyncio +async def test_list_changelogs_async_pages(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_changelogs), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + agent_service.ListChangelogsResponse( + changelogs=[ + changelog.Changelog(), + changelog.Changelog(), + changelog.Changelog(), + ], + next_page_token="abc", + ), + agent_service.ListChangelogsResponse( + changelogs=[], + next_page_token="def", + ), + agent_service.ListChangelogsResponse( + changelogs=[ + changelog.Changelog(), + ], + next_page_token="ghi", + ), + agent_service.ListChangelogsResponse( + changelogs=[ + changelog.Changelog(), + changelog.Changelog(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_changelogs(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.GetChangelogRequest, + dict, + ], +) +def test_get_changelog(request_type, transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_changelog), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = changelog.Changelog( + name="name_value", + author="author_value", + display_name="display_name_value", + description="description_value", + resource="resource_value", + resource_type="resource_type_value", + action="action_value", + sequence_number=1601, + ) + response = client.get_changelog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = agent_service.GetChangelogRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, changelog.Changelog) + assert response.name == "name_value" + assert response.author == "author_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.resource == "resource_value" + assert response.resource_type == "resource_type_value" + assert response.action == "action_value" + assert response.sequence_number == 1601 + + +def test_get_changelog_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = agent_service.GetChangelogRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_changelog), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_changelog(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == agent_service.GetChangelogRequest( + name="name_value", + ) + + +def test_get_changelog_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_changelog in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_changelog] = mock_rpc + request = {} + client.get_changelog(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_changelog(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_changelog_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_changelog + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_changelog + ] = mock_rpc + + request = {} + await client.get_changelog(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_changelog(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_changelog_async( + transport: str = "grpc_asyncio", request_type=agent_service.GetChangelogRequest +): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_changelog), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + changelog.Changelog( + name="name_value", + author="author_value", + display_name="display_name_value", + description="description_value", + resource="resource_value", + resource_type="resource_type_value", + action="action_value", + sequence_number=1601, + ) + ) + response = await client.get_changelog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = agent_service.GetChangelogRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, changelog.Changelog) + assert response.name == "name_value" + assert response.author == "author_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.resource == "resource_value" + assert response.resource_type == "resource_type_value" + assert response.action == "action_value" + assert response.sequence_number == 1601 + + +@pytest.mark.asyncio +async def test_get_changelog_async_from_dict(): + await test_get_changelog_async(request_type=dict) + + +def test_get_changelog_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.GetChangelogRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_changelog), "__call__") as call: + call.return_value = changelog.Changelog() + client.get_changelog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_changelog_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = agent_service.GetChangelogRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_changelog), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(changelog.Changelog()) + await client.get_changelog(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_changelog_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_changelog), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = changelog.Changelog() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_changelog( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_changelog_flattened_error(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_changelog( + agent_service.GetChangelogRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_changelog_flattened_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_changelog), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = changelog.Changelog() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(changelog.Changelog()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_changelog( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_changelog_flattened_error_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_changelog( + agent_service.GetChangelogRequest(), + name="name_value", + ) + + +def test_list_apps_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_apps in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_apps] = mock_rpc + + request = {} + client.list_apps(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_apps(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_apps_rest_required_fields(request_type=agent_service.ListAppsRequest): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_apps._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_apps._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = agent_service.ListAppsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = agent_service.ListAppsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_apps(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_apps_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_apps._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_apps_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = agent_service.ListAppsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = agent_service.ListAppsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_apps(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*}/apps" % client.transport._host, + args[1], + ) + + +def test_list_apps_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_apps( + agent_service.ListAppsRequest(), + parent="parent_value", + ) + + +def test_list_apps_rest_pager(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + agent_service.ListAppsResponse( + apps=[ + app.App(), + app.App(), + app.App(), + ], + next_page_token="abc", + ), + agent_service.ListAppsResponse( + apps=[], + next_page_token="def", + ), + agent_service.ListAppsResponse( + apps=[ + app.App(), + ], + next_page_token="ghi", + ), + agent_service.ListAppsResponse( + apps=[ + app.App(), + app.App(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(agent_service.ListAppsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_apps(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, app.App) for i in results) + + pages = list(client.list_apps(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_app_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_app in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_app] = mock_rpc + + request = {} + client.get_app(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_app(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_app_rest_required_fields(request_type=agent_service.GetAppRequest): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_app._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_app._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = app.App() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = app.App.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_app(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_app_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_app._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_app_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = app.App() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/apps/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = app.App.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_app(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/apps/*}" % client.transport._host, + args[1], + ) + + +def test_get_app_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_app( + agent_service.GetAppRequest(), + name="name_value", + ) + + +def test_create_app_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_app in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_app] = mock_rpc + + request = {} + client.create_app(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_app(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_app_rest_required_fields(request_type=agent_service.CreateAppRequest): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_app._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_app._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("app_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_app(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_app_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_app._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("appId",)) + & set( + ( + "parent", + "app", + ) + ) + ) + + +def test_create_app_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + app=gcc_app.App(name="name_value"), + app_id="app_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_app(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*}/apps" % client.transport._host, + args[1], + ) + + +def test_create_app_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_app( + agent_service.CreateAppRequest(), + parent="parent_value", + app=gcc_app.App(name="name_value"), + app_id="app_id_value", + ) + + +def test_update_app_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_app in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_app] = mock_rpc + + request = {} + client.update_app(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_app(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_app_rest_required_fields(request_type=agent_service.UpdateAppRequest): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_app._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_app._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcc_app.App() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcc_app.App.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_app(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_app_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_app._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("app",))) + + +def test_update_app_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcc_app.App() + + # get arguments that satisfy an http rule for this method + sample_request = { + "app": {"name": "projects/sample1/locations/sample2/apps/sample3"} + } + + # get truthy value for each flattened field + mock_args = dict( + app=gcc_app.App(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcc_app.App.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_app(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{app.name=projects/*/locations/*/apps/*}" + % client.transport._host, + args[1], + ) + + +def test_update_app_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_app( + agent_service.UpdateAppRequest(), + app=gcc_app.App(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_app_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_app in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_app] = mock_rpc + + request = {} + client.delete_app(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_app(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_app_rest_required_fields(request_type=agent_service.DeleteAppRequest): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_app._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_app._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("etag",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_app(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_app_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_app._get_unset_required_fields({}) + assert set(unset_fields) == (set(("etag",)) & set(("name",))) + + +def test_delete_app_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/apps/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_app(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/apps/*}" % client.transport._host, + args[1], + ) + + +def test_delete_app_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_app( + agent_service.DeleteAppRequest(), + name="name_value", + ) + + +def test_export_app_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.export_app in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.export_app] = mock_rpc + + request = {} + client.export_app(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.export_app(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_export_app_rest_required_fields(request_type=agent_service.ExportAppRequest): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).export_app._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).export_app._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.export_app(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_export_app_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.export_app._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "name", + "exportFormat", + ) + ) + ) + + +def test_export_app_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/apps/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.export_app(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/apps/*}:exportApp" + % client.transport._host, + args[1], + ) + + +def test_export_app_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.export_app( + agent_service.ExportAppRequest(), + name="name_value", + ) + + +def test_import_app_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.import_app in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.import_app] = mock_rpc + + request = {} + client.import_app(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.import_app(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_import_app_rest_required_fields(request_type=agent_service.ImportAppRequest): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).import_app._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).import_app._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.import_app(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_import_app_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.import_app._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent",))) + + +def test_import_app_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + display_name="display_name_value", + app_id="app_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.import_app(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*}/apps:importApp" + % client.transport._host, + args[1], + ) + + +def test_import_app_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.import_app( + agent_service.ImportAppRequest(), + parent="parent_value", + display_name="display_name_value", + app_id="app_id_value", + ) + + +def test_list_agents_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_agents in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_agents] = mock_rpc + + request = {} + client.list_agents(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_agents(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_agents_rest_required_fields(request_type=agent_service.ListAgentsRequest): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_agents._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_agents._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = agent_service.ListAgentsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = agent_service.ListAgentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_agents(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_agents_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_agents._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_agents_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = agent_service.ListAgentsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = agent_service.ListAgentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_agents(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*/apps/*}/agents" + % client.transport._host, + args[1], + ) + + +def test_list_agents_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_agents( + agent_service.ListAgentsRequest(), + parent="parent_value", + ) + + +def test_list_agents_rest_pager(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + agent_service.ListAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + agent.Agent(), + ], + next_page_token="abc", + ), + agent_service.ListAgentsResponse( + agents=[], + next_page_token="def", + ), + agent_service.ListAgentsResponse( + agents=[ + agent.Agent(), + ], + next_page_token="ghi", + ), + agent_service.ListAgentsResponse( + agents=[ + agent.Agent(), + agent.Agent(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(agent_service.ListAgentsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + pager = client.list_agents(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, agent.Agent) for i in results) + + pages = list(client.list_agents(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_agent_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_agent in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_agent] = mock_rpc + + request = {} + client.get_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_agent(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_agent_rest_required_fields(request_type=agent_service.GetAgentRequest): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_agent._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_agent._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = agent.Agent() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = agent.Agent.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_agent(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_agent_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_agent._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_agent_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = agent.Agent() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/apps/sample3/agents/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = agent.Agent.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_agent(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/apps/*/agents/*}" + % client.transport._host, + args[1], + ) + + +def test_get_agent_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_agent( + agent_service.GetAgentRequest(), + name="name_value", + ) + + +def test_create_agent_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_agent in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_agent] = mock_rpc + + request = {} + client.create_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_agent(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_agent_rest_required_fields( + request_type=agent_service.CreateAgentRequest, +): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_agent._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_agent._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("agent_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcc_agent.Agent() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcc_agent.Agent.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_agent(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_agent_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_agent._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("agentId",)) + & set( + ( + "parent", + "agent", + ) + ) + ) + + +def test_create_agent_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcc_agent.Agent() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + agent=gcc_agent.Agent(llm_agent=None), + agent_id="agent_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcc_agent.Agent.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_agent(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*/apps/*}/agents" + % client.transport._host, + args[1], + ) + + +def test_create_agent_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_agent( + agent_service.CreateAgentRequest(), + parent="parent_value", + agent=gcc_agent.Agent(llm_agent=None), + agent_id="agent_id_value", + ) + + +def test_update_agent_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_agent in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_agent] = mock_rpc + + request = {} + client.update_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_agent(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_agent_rest_required_fields( + request_type=agent_service.UpdateAgentRequest, +): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_agent._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_agent._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcc_agent.Agent() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcc_agent.Agent.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_agent(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_agent_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_agent._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("agent",))) + + +def test_update_agent_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcc_agent.Agent() + + # get arguments that satisfy an http rule for this method + sample_request = { + "agent": { + "name": "projects/sample1/locations/sample2/apps/sample3/agents/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + agent=gcc_agent.Agent(llm_agent=None), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcc_agent.Agent.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_agent(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{agent.name=projects/*/locations/*/apps/*/agents/*}" + % client.transport._host, + args[1], + ) + + +def test_update_agent_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_agent( + agent_service.UpdateAgentRequest(), + agent=gcc_agent.Agent(llm_agent=None), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_agent_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_agent in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_agent] = mock_rpc + + request = {} + client.delete_agent(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_agent(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_agent_rest_required_fields( + request_type=agent_service.DeleteAgentRequest, +): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_agent._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_agent._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "etag", + "force", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_agent(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_agent_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_agent._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "etag", + "force", + ) + ) + & set(("name",)) + ) + + +def test_delete_agent_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/apps/sample3/agents/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_agent(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/apps/*/agents/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_agent_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_agent( + agent_service.DeleteAgentRequest(), + name="name_value", + ) + + +def test_list_examples_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_examples in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_examples] = mock_rpc + + request = {} + client.list_examples(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_examples(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_examples_rest_required_fields( + request_type=agent_service.ListExamplesRequest, +): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_examples._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_examples._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = agent_service.ListExamplesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = agent_service.ListExamplesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_examples(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_examples_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_examples._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_examples_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = agent_service.ListExamplesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = agent_service.ListExamplesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_examples(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*/apps/*}/examples" + % client.transport._host, + args[1], + ) + + +def test_list_examples_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_examples( + agent_service.ListExamplesRequest(), + parent="parent_value", + ) + + +def test_list_examples_rest_pager(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + agent_service.ListExamplesResponse( + examples=[ + example.Example(), + example.Example(), + example.Example(), + ], + next_page_token="abc", + ), + agent_service.ListExamplesResponse( + examples=[], + next_page_token="def", + ), + agent_service.ListExamplesResponse( + examples=[ + example.Example(), + ], + next_page_token="ghi", + ), + agent_service.ListExamplesResponse( + examples=[ + example.Example(), + example.Example(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + agent_service.ListExamplesResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + pager = client.list_examples(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, example.Example) for i in results) + + pages = list(client.list_examples(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_example_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_example in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_example] = mock_rpc + + request = {} + client.get_example(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_example(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_example_rest_required_fields(request_type=agent_service.GetExampleRequest): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_example._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_example._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = example.Example() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = example.Example.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_example(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_example_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_example._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_example_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = example.Example() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/apps/sample3/examples/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = example.Example.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_example(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/apps/*/examples/*}" + % client.transport._host, + args[1], + ) + + +def test_get_example_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_example( + agent_service.GetExampleRequest(), + name="name_value", + ) + + +def test_create_example_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_example in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_example] = mock_rpc + + request = {} + client.create_example(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_example(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_example_rest_required_fields( + request_type=agent_service.CreateExampleRequest, +): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_example._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_example._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("example_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcc_example.Example() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcc_example.Example.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_example(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_example_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_example._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("exampleId",)) + & set( + ( + "parent", + "example", + ) + ) + ) + + +def test_create_example_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcc_example.Example() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + example=gcc_example.Example(name="name_value"), + example_id="example_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcc_example.Example.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_example(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*/apps/*}/examples" + % client.transport._host, + args[1], + ) + + +def test_create_example_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_example( + agent_service.CreateExampleRequest(), + parent="parent_value", + example=gcc_example.Example(name="name_value"), + example_id="example_id_value", + ) + + +def test_update_example_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_example in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_example] = mock_rpc + + request = {} + client.update_example(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_example(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_example_rest_required_fields( + request_type=agent_service.UpdateExampleRequest, +): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_example._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_example._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcc_example.Example() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcc_example.Example.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_example(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_example_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_example._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("example",))) + + +def test_update_example_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcc_example.Example() + + # get arguments that satisfy an http rule for this method + sample_request = { + "example": { + "name": "projects/sample1/locations/sample2/apps/sample3/examples/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + example=gcc_example.Example(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcc_example.Example.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_example(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{example.name=projects/*/locations/*/apps/*/examples/*}" + % client.transport._host, + args[1], + ) + + +def test_update_example_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_example( + agent_service.UpdateExampleRequest(), + example=gcc_example.Example(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_example_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_example in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_example] = mock_rpc + + request = {} + client.delete_example(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_example(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_example_rest_required_fields( + request_type=agent_service.DeleteExampleRequest, +): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_example._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_example._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("etag",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_example(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_example_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_example._get_unset_required_fields({}) + assert set(unset_fields) == (set(("etag",)) & set(("name",))) + + +def test_delete_example_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/apps/sample3/examples/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_example(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/apps/*/examples/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_example_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_example( + agent_service.DeleteExampleRequest(), + name="name_value", + ) + + +def test_list_tools_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_tools in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_tools] = mock_rpc + + request = {} + client.list_tools(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_tools(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_tools_rest_required_fields(request_type=agent_service.ListToolsRequest): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_tools._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_tools._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = agent_service.ListToolsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = agent_service.ListToolsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_tools(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_tools_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_tools._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_tools_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = agent_service.ListToolsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = agent_service.ListToolsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_tools(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*/apps/*}/tools" + % client.transport._host, + args[1], + ) + + +def test_list_tools_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_tools( + agent_service.ListToolsRequest(), + parent="parent_value", + ) + + +def test_list_tools_rest_pager(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + agent_service.ListToolsResponse( + tools=[ + tool.Tool(), + tool.Tool(), + tool.Tool(), + ], + next_page_token="abc", + ), + agent_service.ListToolsResponse( + tools=[], + next_page_token="def", + ), + agent_service.ListToolsResponse( + tools=[ + tool.Tool(), + ], + next_page_token="ghi", + ), + agent_service.ListToolsResponse( + tools=[ + tool.Tool(), + tool.Tool(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(agent_service.ListToolsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + pager = client.list_tools(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, tool.Tool) for i in results) + + pages = list(client.list_tools(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_tool_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_tool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_tool] = mock_rpc + + request = {} + client.get_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_tool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_tool_rest_required_fields(request_type=agent_service.GetToolRequest): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_tool._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_tool._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = tool.Tool() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = tool.Tool.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_tool(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_tool_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_tool._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_tool_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = tool.Tool() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/apps/sample3/tools/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = tool.Tool.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_tool(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/apps/*/tools/*}" + % client.transport._host, + args[1], + ) + + +def test_get_tool_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_tool( + agent_service.GetToolRequest(), + name="name_value", + ) + + +def test_list_conversations_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_conversations in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_conversations] = ( + mock_rpc + ) + + request = {} + client.list_conversations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_conversations(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_conversations_rest_required_fields( + request_type=agent_service.ListConversationsRequest, +): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_conversations._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_conversations._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "page_size", + "page_token", + "source", + "sources", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = agent_service.ListConversationsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = agent_service.ListConversationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_conversations(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_conversations_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_conversations._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "pageSize", + "pageToken", + "source", + "sources", + ) + ) + & set(("parent",)) + ) + + +def test_list_conversations_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = agent_service.ListConversationsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = agent_service.ListConversationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_conversations(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*/apps/*}/conversations" + % client.transport._host, + args[1], + ) + + +def test_list_conversations_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_conversations( + agent_service.ListConversationsRequest(), + parent="parent_value", + ) + + +def test_list_conversations_rest_pager(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + agent_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + conversation.Conversation(), + ], + next_page_token="abc", + ), + agent_service.ListConversationsResponse( + conversations=[], + next_page_token="def", + ), + agent_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + ], + next_page_token="ghi", + ), + agent_service.ListConversationsResponse( + conversations=[ + conversation.Conversation(), + conversation.Conversation(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + agent_service.ListConversationsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + pager = client.list_conversations(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, conversation.Conversation) for i in results) + + pages = list(client.list_conversations(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_conversation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_conversation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_conversation] = ( + mock_rpc + ) + + request = {} + client.get_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_conversation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_conversation_rest_required_fields( + request_type=agent_service.GetConversationRequest, +): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_conversation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_conversation._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("source",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = conversation.Conversation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = conversation.Conversation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_conversation(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_conversation_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_conversation._get_unset_required_fields({}) + assert set(unset_fields) == (set(("source",)) & set(("name",))) + + +def test_get_conversation_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = conversation.Conversation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/apps/sample3/conversations/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = conversation.Conversation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_conversation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/apps/*/conversations/*}" + % client.transport._host, + args[1], + ) + + +def test_get_conversation_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_conversation( + agent_service.GetConversationRequest(), + name="name_value", + ) + + +def test_delete_conversation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_conversation in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_conversation] = ( + mock_rpc + ) + + request = {} + client.delete_conversation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_conversation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_conversation_rest_required_fields( + request_type=agent_service.DeleteConversationRequest, +): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_conversation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_conversation._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("source",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_conversation(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_conversation_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_conversation._get_unset_required_fields({}) + assert set(unset_fields) == (set(("source",)) & set(("name",))) + + +def test_delete_conversation_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/apps/sample3/conversations/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_conversation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/apps/*/conversations/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_conversation_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_conversation( + agent_service.DeleteConversationRequest(), + name="name_value", + ) + + +def test_batch_delete_conversations_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.batch_delete_conversations + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.batch_delete_conversations + ] = mock_rpc + + request = {} + client.batch_delete_conversations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.batch_delete_conversations(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_batch_delete_conversations_rest_required_fields( + request_type=agent_service.BatchDeleteConversationsRequest, +): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["conversations"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_delete_conversations._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + jsonified_request["conversations"] = "conversations_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_delete_conversations._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "conversations" in jsonified_request + assert jsonified_request["conversations"] == "conversations_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.batch_delete_conversations(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_batch_delete_conversations_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.batch_delete_conversations._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "conversations", + ) + ) + ) + + +def test_batch_delete_conversations_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.batch_delete_conversations(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*/apps/*}/conversations:batchDelete" + % client.transport._host, + args[1], + ) + + +def test_batch_delete_conversations_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_delete_conversations( + agent_service.BatchDeleteConversationsRequest(), + parent="parent_value", + ) + + +def test_create_tool_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_tool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_tool] = mock_rpc + + request = {} + client.create_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_tool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_tool_rest_required_fields(request_type=agent_service.CreateToolRequest): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_tool._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_tool._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("tool_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcc_tool.Tool() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcc_tool.Tool.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_tool(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_tool_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_tool._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("toolId",)) + & set( + ( + "parent", + "tool", + ) + ) + ) + + +def test_create_tool_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcc_tool.Tool() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + tool=gcc_tool.Tool( + client_function=client_function.ClientFunction(name="name_value") + ), + tool_id="tool_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcc_tool.Tool.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_tool(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*/apps/*}/tools" + % client.transport._host, + args[1], + ) + + +def test_create_tool_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_tool( + agent_service.CreateToolRequest(), + parent="parent_value", + tool=gcc_tool.Tool( + client_function=client_function.ClientFunction(name="name_value") + ), + tool_id="tool_id_value", + ) + + +def test_update_tool_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_tool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_tool] = mock_rpc + + request = {} + client.update_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_tool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_tool_rest_required_fields(request_type=agent_service.UpdateToolRequest): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_tool._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_tool._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcc_tool.Tool() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcc_tool.Tool.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_tool(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_tool_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_tool._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("tool",))) + + +def test_update_tool_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcc_tool.Tool() + + # get arguments that satisfy an http rule for this method + sample_request = { + "tool": { + "name": "projects/sample1/locations/sample2/apps/sample3/tools/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + tool=gcc_tool.Tool( + client_function=client_function.ClientFunction(name="name_value") + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcc_tool.Tool.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_tool(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{tool.name=projects/*/locations/*/apps/*/tools/*}" + % client.transport._host, + args[1], + ) + + +def test_update_tool_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_tool( + agent_service.UpdateToolRequest(), + tool=gcc_tool.Tool( + client_function=client_function.ClientFunction(name="name_value") + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_tool_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_tool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_tool] = mock_rpc + + request = {} + client.delete_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_tool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_tool_rest_required_fields(request_type=agent_service.DeleteToolRequest): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_tool._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_tool._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "etag", + "force", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_tool(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_tool_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_tool._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "etag", + "force", + ) + ) + & set(("name",)) + ) + + +def test_delete_tool_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/apps/sample3/tools/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_tool(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/apps/*/tools/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_tool_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_tool( + agent_service.DeleteToolRequest(), + name="name_value", + ) + + +def test_list_guardrails_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_guardrails in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_guardrails] = mock_rpc + + request = {} + client.list_guardrails(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_guardrails(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_guardrails_rest_required_fields( + request_type=agent_service.ListGuardrailsRequest, +): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_guardrails._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_guardrails._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = agent_service.ListGuardrailsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = agent_service.ListGuardrailsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_guardrails(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_guardrails_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_guardrails._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_guardrails_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = agent_service.ListGuardrailsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = agent_service.ListGuardrailsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_guardrails(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*/apps/*}/guardrails" + % client.transport._host, + args[1], + ) + + +def test_list_guardrails_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_guardrails( + agent_service.ListGuardrailsRequest(), + parent="parent_value", + ) + + +def test_list_guardrails_rest_pager(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + agent_service.ListGuardrailsResponse( + guardrails=[ + guardrail.Guardrail(), + guardrail.Guardrail(), + guardrail.Guardrail(), + ], + next_page_token="abc", + ), + agent_service.ListGuardrailsResponse( + guardrails=[], + next_page_token="def", + ), + agent_service.ListGuardrailsResponse( + guardrails=[ + guardrail.Guardrail(), + ], + next_page_token="ghi", + ), + agent_service.ListGuardrailsResponse( + guardrails=[ + guardrail.Guardrail(), + guardrail.Guardrail(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + agent_service.ListGuardrailsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + pager = client.list_guardrails(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, guardrail.Guardrail) for i in results) + + pages = list(client.list_guardrails(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_guardrail_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_guardrail in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_guardrail] = mock_rpc + + request = {} + client.get_guardrail(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_guardrail(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_guardrail_rest_required_fields( + request_type=agent_service.GetGuardrailRequest, +): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_guardrail._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_guardrail._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = guardrail.Guardrail() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = guardrail.Guardrail.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_guardrail(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_guardrail_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_guardrail._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_guardrail_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = guardrail.Guardrail() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/apps/sample3/guardrails/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = guardrail.Guardrail.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_guardrail(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/apps/*/guardrails/*}" + % client.transport._host, + args[1], + ) + + +def test_get_guardrail_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_guardrail( + agent_service.GetGuardrailRequest(), + name="name_value", + ) + + +def test_create_guardrail_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_guardrail in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_guardrail] = ( + mock_rpc + ) + + request = {} + client.create_guardrail(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_guardrail(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_guardrail_rest_required_fields( + request_type=agent_service.CreateGuardrailRequest, +): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_guardrail._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_guardrail._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("guardrail_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcc_guardrail.Guardrail() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcc_guardrail.Guardrail.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_guardrail(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_guardrail_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_guardrail._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("guardrailId",)) + & set( + ( + "parent", + "guardrail", + ) + ) + ) + + +def test_create_guardrail_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcc_guardrail.Guardrail() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + guardrail=gcc_guardrail.Guardrail( + content_filter=gcc_guardrail.Guardrail.ContentFilter( + banned_contents=["banned_contents_value"] + ) + ), + guardrail_id="guardrail_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcc_guardrail.Guardrail.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_guardrail(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*/apps/*}/guardrails" + % client.transport._host, + args[1], + ) + + +def test_create_guardrail_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_guardrail( + agent_service.CreateGuardrailRequest(), + parent="parent_value", + guardrail=gcc_guardrail.Guardrail( + content_filter=gcc_guardrail.Guardrail.ContentFilter( + banned_contents=["banned_contents_value"] + ) + ), + guardrail_id="guardrail_id_value", + ) + + +def test_update_guardrail_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_guardrail in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_guardrail] = ( + mock_rpc + ) + + request = {} + client.update_guardrail(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_guardrail(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_guardrail_rest_required_fields( + request_type=agent_service.UpdateGuardrailRequest, +): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_guardrail._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_guardrail._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcc_guardrail.Guardrail() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcc_guardrail.Guardrail.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_guardrail(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_guardrail_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_guardrail._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("guardrail",))) + + +def test_update_guardrail_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcc_guardrail.Guardrail() + + # get arguments that satisfy an http rule for this method + sample_request = { + "guardrail": { + "name": "projects/sample1/locations/sample2/apps/sample3/guardrails/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + guardrail=gcc_guardrail.Guardrail( + content_filter=gcc_guardrail.Guardrail.ContentFilter( + banned_contents=["banned_contents_value"] + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcc_guardrail.Guardrail.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_guardrail(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{guardrail.name=projects/*/locations/*/apps/*/guardrails/*}" + % client.transport._host, + args[1], + ) + + +def test_update_guardrail_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_guardrail( + agent_service.UpdateGuardrailRequest(), + guardrail=gcc_guardrail.Guardrail( + content_filter=gcc_guardrail.Guardrail.ContentFilter( + banned_contents=["banned_contents_value"] + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_guardrail_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_guardrail in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_guardrail] = ( + mock_rpc + ) + + request = {} + client.delete_guardrail(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_guardrail(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_guardrail_rest_required_fields( + request_type=agent_service.DeleteGuardrailRequest, +): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_guardrail._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_guardrail._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "etag", + "force", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_guardrail(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_guardrail_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_guardrail._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "etag", + "force", + ) + ) + & set(("name",)) + ) + + +def test_delete_guardrail_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/apps/sample3/guardrails/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_guardrail(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/apps/*/guardrails/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_guardrail_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_guardrail( + agent_service.DeleteGuardrailRequest(), + name="name_value", + ) + + +def test_list_deployments_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_deployments in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_deployments] = ( + mock_rpc + ) + + request = {} + client.list_deployments(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_deployments(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_deployments_rest_required_fields( + request_type=agent_service.ListDeploymentsRequest, +): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_deployments._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_deployments._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = agent_service.ListDeploymentsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = agent_service.ListDeploymentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_deployments(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_deployments_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_deployments._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_deployments_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = agent_service.ListDeploymentsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = agent_service.ListDeploymentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_deployments(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*/apps/*}/deployments" + % client.transport._host, + args[1], + ) + + +def test_list_deployments_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_deployments( + agent_service.ListDeploymentsRequest(), + parent="parent_value", + ) + + +def test_list_deployments_rest_pager(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + agent_service.ListDeploymentsResponse( + deployments=[ + deployment.Deployment(), + deployment.Deployment(), + deployment.Deployment(), + ], + next_page_token="abc", + ), + agent_service.ListDeploymentsResponse( + deployments=[], + next_page_token="def", + ), + agent_service.ListDeploymentsResponse( + deployments=[ + deployment.Deployment(), + ], + next_page_token="ghi", + ), + agent_service.ListDeploymentsResponse( + deployments=[ + deployment.Deployment(), + deployment.Deployment(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + agent_service.ListDeploymentsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + pager = client.list_deployments(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, deployment.Deployment) for i in results) + + pages = list(client.list_deployments(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_deployment_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_deployment in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_deployment] = mock_rpc + + request = {} + client.get_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_deployment(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_deployment_rest_required_fields( + request_type=agent_service.GetDeploymentRequest, +): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_deployment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_deployment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = deployment.Deployment() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = deployment.Deployment.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_deployment(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_deployment_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_deployment._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_deployment_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = deployment.Deployment() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/apps/sample3/deployments/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = deployment.Deployment.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_deployment(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/apps/*/deployments/*}" + % client.transport._host, + args[1], + ) + + +def test_get_deployment_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_deployment( + agent_service.GetDeploymentRequest(), + name="name_value", + ) + + +def test_create_deployment_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_deployment in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_deployment] = ( + mock_rpc + ) + + request = {} + client.create_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_deployment(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_deployment_rest_required_fields( + request_type=agent_service.CreateDeploymentRequest, +): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_deployment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_deployment._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("deployment_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcc_deployment.Deployment() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcc_deployment.Deployment.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_deployment(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_deployment_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_deployment._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("deploymentId",)) + & set( + ( + "parent", + "deployment", + ) + ) + ) + + +def test_create_deployment_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcc_deployment.Deployment() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + deployment=gcc_deployment.Deployment(name="name_value"), + deployment_id="deployment_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcc_deployment.Deployment.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_deployment(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*/apps/*}/deployments" + % client.transport._host, + args[1], + ) + + +def test_create_deployment_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_deployment( + agent_service.CreateDeploymentRequest(), + parent="parent_value", + deployment=gcc_deployment.Deployment(name="name_value"), + deployment_id="deployment_id_value", + ) + + +def test_update_deployment_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_deployment in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_deployment] = ( + mock_rpc + ) + + request = {} + client.update_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_deployment(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_deployment_rest_required_fields( + request_type=agent_service.UpdateDeploymentRequest, +): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_deployment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_deployment._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcc_deployment.Deployment() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcc_deployment.Deployment.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_deployment(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_deployment_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_deployment._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("deployment",))) + + +def test_update_deployment_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcc_deployment.Deployment() + + # get arguments that satisfy an http rule for this method + sample_request = { + "deployment": { + "name": "projects/sample1/locations/sample2/apps/sample3/deployments/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + deployment=gcc_deployment.Deployment(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcc_deployment.Deployment.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_deployment(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{deployment.name=projects/*/locations/*/apps/*/deployments/*}" + % client.transport._host, + args[1], + ) + + +def test_update_deployment_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_deployment( + agent_service.UpdateDeploymentRequest(), + deployment=gcc_deployment.Deployment(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_deployment_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_deployment in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_deployment] = ( + mock_rpc + ) + + request = {} + client.delete_deployment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_deployment(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_deployment_rest_required_fields( + request_type=agent_service.DeleteDeploymentRequest, +): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_deployment._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_deployment._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("etag",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_deployment(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_deployment_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_deployment._get_unset_required_fields({}) + assert set(unset_fields) == (set(("etag",)) & set(("name",))) + + +def test_delete_deployment_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/apps/sample3/deployments/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_deployment(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/apps/*/deployments/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_deployment_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_deployment( + agent_service.DeleteDeploymentRequest(), + name="name_value", + ) + + +def test_list_toolsets_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_toolsets in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_toolsets] = mock_rpc + + request = {} + client.list_toolsets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_toolsets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_toolsets_rest_required_fields( + request_type=agent_service.ListToolsetsRequest, +): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_toolsets._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_toolsets._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = agent_service.ListToolsetsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = agent_service.ListToolsetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_toolsets(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_toolsets_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_toolsets._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_toolsets_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = agent_service.ListToolsetsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = agent_service.ListToolsetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_toolsets(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*/apps/*}/toolsets" + % client.transport._host, + args[1], + ) + + +def test_list_toolsets_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_toolsets( + agent_service.ListToolsetsRequest(), + parent="parent_value", + ) + + +def test_list_toolsets_rest_pager(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + agent_service.ListToolsetsResponse( + toolsets=[ + toolset.Toolset(), + toolset.Toolset(), + toolset.Toolset(), + ], + next_page_token="abc", + ), + agent_service.ListToolsetsResponse( + toolsets=[], + next_page_token="def", + ), + agent_service.ListToolsetsResponse( + toolsets=[ + toolset.Toolset(), + ], + next_page_token="ghi", + ), + agent_service.ListToolsetsResponse( + toolsets=[ + toolset.Toolset(), + toolset.Toolset(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + agent_service.ListToolsetsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + pager = client.list_toolsets(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, toolset.Toolset) for i in results) + + pages = list(client.list_toolsets(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_toolset_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_toolset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_toolset] = mock_rpc + + request = {} + client.get_toolset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_toolset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_toolset_rest_required_fields(request_type=agent_service.GetToolsetRequest): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_toolset._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_toolset._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = toolset.Toolset() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = toolset.Toolset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_toolset(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_toolset_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_toolset._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_toolset_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = toolset.Toolset() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/apps/sample3/toolsets/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = toolset.Toolset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_toolset(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/apps/*/toolsets/*}" + % client.transport._host, + args[1], + ) + + +def test_get_toolset_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_toolset( + agent_service.GetToolsetRequest(), + name="name_value", + ) + + +def test_create_toolset_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_toolset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_toolset] = mock_rpc + + request = {} + client.create_toolset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_toolset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_toolset_rest_required_fields( + request_type=agent_service.CreateToolsetRequest, +): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_toolset._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_toolset._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("toolset_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcc_toolset.Toolset() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcc_toolset.Toolset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_toolset(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_toolset_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_toolset._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("toolsetId",)) + & set( + ( + "parent", + "toolset", + ) + ) + ) + + +def test_create_toolset_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcc_toolset.Toolset() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + toolset=gcc_toolset.Toolset( + mcp_toolset=mcp_toolset.McpToolset( + server_address="server_address_value" + ) + ), + toolset_id="toolset_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcc_toolset.Toolset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_toolset(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*/apps/*}/toolsets" + % client.transport._host, + args[1], + ) + + +def test_create_toolset_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_toolset( + agent_service.CreateToolsetRequest(), + parent="parent_value", + toolset=gcc_toolset.Toolset( + mcp_toolset=mcp_toolset.McpToolset( + server_address="server_address_value" + ) + ), + toolset_id="toolset_id_value", + ) + + +def test_update_toolset_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_toolset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_toolset] = mock_rpc + + request = {} + client.update_toolset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_toolset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_toolset_rest_required_fields( + request_type=agent_service.UpdateToolsetRequest, +): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_toolset._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_toolset._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcc_toolset.Toolset() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcc_toolset.Toolset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_toolset(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_toolset_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_toolset._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("toolset",))) + + +def test_update_toolset_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcc_toolset.Toolset() + + # get arguments that satisfy an http rule for this method + sample_request = { + "toolset": { + "name": "projects/sample1/locations/sample2/apps/sample3/toolsets/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + toolset=gcc_toolset.Toolset( + mcp_toolset=mcp_toolset.McpToolset( + server_address="server_address_value" + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcc_toolset.Toolset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_toolset(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{toolset.name=projects/*/locations/*/apps/*/toolsets/*}" + % client.transport._host, + args[1], + ) + + +def test_update_toolset_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_toolset( + agent_service.UpdateToolsetRequest(), + toolset=gcc_toolset.Toolset( + mcp_toolset=mcp_toolset.McpToolset( + server_address="server_address_value" + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_toolset_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_toolset in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_toolset] = mock_rpc + + request = {} + client.delete_toolset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_toolset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_toolset_rest_required_fields( + request_type=agent_service.DeleteToolsetRequest, +): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_toolset._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_toolset._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "etag", + "force", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_toolset(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_toolset_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_toolset._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "etag", + "force", + ) + ) + & set(("name",)) + ) + + +def test_delete_toolset_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/apps/sample3/toolsets/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_toolset(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/apps/*/toolsets/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_toolset_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_toolset( + agent_service.DeleteToolsetRequest(), + name="name_value", + ) + + +def test_list_app_versions_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_app_versions in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_app_versions] = ( + mock_rpc + ) + + request = {} + client.list_app_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_app_versions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_app_versions_rest_required_fields( + request_type=agent_service.ListAppVersionsRequest, +): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_app_versions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_app_versions._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = agent_service.ListAppVersionsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = agent_service.ListAppVersionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_app_versions(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_app_versions_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_app_versions._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_app_versions_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = agent_service.ListAppVersionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = agent_service.ListAppVersionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_app_versions(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*/apps/*}/versions" + % client.transport._host, + args[1], + ) + + +def test_list_app_versions_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_app_versions( + agent_service.ListAppVersionsRequest(), + parent="parent_value", + ) + + +def test_list_app_versions_rest_pager(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + agent_service.ListAppVersionsResponse( + app_versions=[ + app_version.AppVersion(), + app_version.AppVersion(), + app_version.AppVersion(), + ], + next_page_token="abc", + ), + agent_service.ListAppVersionsResponse( + app_versions=[], + next_page_token="def", + ), + agent_service.ListAppVersionsResponse( + app_versions=[ + app_version.AppVersion(), + ], + next_page_token="ghi", + ), + agent_service.ListAppVersionsResponse( + app_versions=[ + app_version.AppVersion(), + app_version.AppVersion(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + agent_service.ListAppVersionsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + pager = client.list_app_versions(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, app_version.AppVersion) for i in results) + + pages = list(client.list_app_versions(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_app_version_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_app_version in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_app_version] = mock_rpc + + request = {} + client.get_app_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_app_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_app_version_rest_required_fields( + request_type=agent_service.GetAppVersionRequest, +): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_app_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_app_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = app_version.AppVersion() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = app_version.AppVersion.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_app_version(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_app_version_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_app_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_app_version_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = app_version.AppVersion() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/apps/sample3/versions/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = app_version.AppVersion.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_app_version(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/apps/*/versions/*}" + % client.transport._host, + args[1], + ) + + +def test_get_app_version_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_app_version( + agent_service.GetAppVersionRequest(), + name="name_value", + ) + + +def test_create_app_version_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_app_version in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_app_version] = ( + mock_rpc + ) + + request = {} + client.create_app_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_app_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_app_version_rest_required_fields( + request_type=agent_service.CreateAppVersionRequest, +): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_app_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_app_version._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("app_version_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcc_app_version.AppVersion() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcc_app_version.AppVersion.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_app_version(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_app_version_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_app_version._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("appVersionId",)) + & set( + ( + "parent", + "appVersion", + ) + ) + ) + + +def test_create_app_version_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcc_app_version.AppVersion() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + app_version=gcc_app_version.AppVersion(name="name_value"), + app_version_id="app_version_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcc_app_version.AppVersion.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_app_version(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*/apps/*}/versions" + % client.transport._host, + args[1], + ) + + +def test_create_app_version_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_app_version( + agent_service.CreateAppVersionRequest(), + parent="parent_value", + app_version=gcc_app_version.AppVersion(name="name_value"), + app_version_id="app_version_id_value", + ) + + +def test_delete_app_version_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_app_version in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_app_version] = ( + mock_rpc + ) + + request = {} + client.delete_app_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_app_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_app_version_rest_required_fields( + request_type=agent_service.DeleteAppVersionRequest, +): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_app_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_app_version._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("etag",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_app_version(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_app_version_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_app_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(("etag",)) & set(("name",))) + + +def test_delete_app_version_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/apps/sample3/versions/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_app_version(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/apps/*/versions/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_app_version_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_app_version( + agent_service.DeleteAppVersionRequest(), + name="name_value", + ) + + +def test_restore_app_version_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.restore_app_version in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.restore_app_version] = ( + mock_rpc + ) + + request = {} + client.restore_app_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.restore_app_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_restore_app_version_rest_required_fields( + request_type=agent_service.RestoreAppVersionRequest, +): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).restore_app_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).restore_app_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.restore_app_version(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_restore_app_version_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.restore_app_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_restore_app_version_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/apps/sample3/versions/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.restore_app_version(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/apps/*/versions/*}:restore" + % client.transport._host, + args[1], + ) + + +def test_restore_app_version_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.restore_app_version( + agent_service.RestoreAppVersionRequest(), + name="name_value", + ) + + +def test_list_changelogs_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_changelogs in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_changelogs] = mock_rpc + + request = {} + client.list_changelogs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_changelogs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_changelogs_rest_required_fields( + request_type=agent_service.ListChangelogsRequest, +): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_changelogs._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_changelogs._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = agent_service.ListChangelogsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = agent_service.ListChangelogsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_changelogs(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_changelogs_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_changelogs._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_changelogs_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = agent_service.ListChangelogsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = agent_service.ListChangelogsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_changelogs(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*/apps/*}/changelogs" + % client.transport._host, + args[1], + ) + + +def test_list_changelogs_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_changelogs( + agent_service.ListChangelogsRequest(), + parent="parent_value", + ) + + +def test_list_changelogs_rest_pager(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + agent_service.ListChangelogsResponse( + changelogs=[ + changelog.Changelog(), + changelog.Changelog(), + changelog.Changelog(), + ], + next_page_token="abc", + ), + agent_service.ListChangelogsResponse( + changelogs=[], + next_page_token="def", + ), + agent_service.ListChangelogsResponse( + changelogs=[ + changelog.Changelog(), + ], + next_page_token="ghi", + ), + agent_service.ListChangelogsResponse( + changelogs=[ + changelog.Changelog(), + changelog.Changelog(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + agent_service.ListChangelogsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + pager = client.list_changelogs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, changelog.Changelog) for i in results) + + pages = list(client.list_changelogs(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_changelog_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_changelog in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_changelog] = mock_rpc + + request = {} + client.get_changelog(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_changelog(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_changelog_rest_required_fields( + request_type=agent_service.GetChangelogRequest, +): + transport_class = transports.AgentServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_changelog._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_changelog._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = changelog.Changelog() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = changelog.Changelog.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_changelog(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_changelog_rest_unset_required_fields(): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_changelog._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_changelog_rest_flattened(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = changelog.Changelog() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/apps/sample3/changelogs/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = changelog.Changelog.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_changelog(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/apps/*/changelogs/*}" + % client.transport._host, + args[1], + ) + + +def test_get_changelog_rest_flattened_error(transport: str = "rest"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_changelog( + agent_service.GetChangelogRequest(), + name="name_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AgentServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AgentServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AgentServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.AgentServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AgentServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AgentServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AgentServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AgentServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AgentServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AgentServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AgentServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AgentServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AgentServiceGrpcTransport, + transports.AgentServiceGrpcAsyncIOTransport, + transports.AgentServiceRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_kind_grpc(): + transport = AgentServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_apps_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_apps), "__call__") as call: + call.return_value = agent_service.ListAppsResponse() + client.list_apps(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.ListAppsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_app_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_app), "__call__") as call: + call.return_value = app.App() + client.get_app(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.GetAppRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_app_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_app), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_app(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.CreateAppRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_app_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_app), "__call__") as call: + call.return_value = gcc_app.App() + client.update_app(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.UpdateAppRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_app_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_app), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_app(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.DeleteAppRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_export_app_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.export_app), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.export_app(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.ExportAppRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_app_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.import_app), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.import_app(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.ImportAppRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_agents_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_agents), "__call__") as call: + call.return_value = agent_service.ListAgentsResponse() + client.list_agents(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.ListAgentsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_agent_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_agent), "__call__") as call: + call.return_value = agent.Agent() + client.get_agent(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.GetAgentRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_agent_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_agent), "__call__") as call: + call.return_value = gcc_agent.Agent() + client.create_agent(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.CreateAgentRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_agent_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_agent), "__call__") as call: + call.return_value = gcc_agent.Agent() + client.update_agent(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.UpdateAgentRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_agent_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_agent), "__call__") as call: + call.return_value = None + client.delete_agent(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.DeleteAgentRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_examples_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_examples), "__call__") as call: + call.return_value = agent_service.ListExamplesResponse() + client.list_examples(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.ListExamplesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_example_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_example), "__call__") as call: + call.return_value = example.Example() + client.get_example(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.GetExampleRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_example_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_example), "__call__") as call: + call.return_value = gcc_example.Example() + client.create_example(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.CreateExampleRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_example_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_example), "__call__") as call: + call.return_value = gcc_example.Example() + client.update_example(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.UpdateExampleRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_example_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_example), "__call__") as call: + call.return_value = None + client.delete_example(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.DeleteExampleRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_tools_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_tools), "__call__") as call: + call.return_value = agent_service.ListToolsResponse() + client.list_tools(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.ListToolsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_tool_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_tool), "__call__") as call: + call.return_value = tool.Tool() + client.get_tool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.GetToolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_conversations_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), "__call__" + ) as call: + call.return_value = agent_service.ListConversationsResponse() + client.list_conversations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.ListConversationsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_conversation_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_conversation), "__call__") as call: + call.return_value = conversation.Conversation() + client.get_conversation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.GetConversationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_conversation_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversation), "__call__" + ) as call: + call.return_value = None + client.delete_conversation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.DeleteConversationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_delete_conversations_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_conversations), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.batch_delete_conversations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.BatchDeleteConversationsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_tool_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_tool), "__call__") as call: + call.return_value = gcc_tool.Tool() + client.create_tool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.CreateToolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_tool_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_tool), "__call__") as call: + call.return_value = gcc_tool.Tool() + client.update_tool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.UpdateToolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_tool_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_tool), "__call__") as call: + call.return_value = None + client.delete_tool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.DeleteToolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_guardrails_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_guardrails), "__call__") as call: + call.return_value = agent_service.ListGuardrailsResponse() + client.list_guardrails(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.ListGuardrailsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_guardrail_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_guardrail), "__call__") as call: + call.return_value = guardrail.Guardrail() + client.get_guardrail(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.GetGuardrailRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_guardrail_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_guardrail), "__call__") as call: + call.return_value = gcc_guardrail.Guardrail() + client.create_guardrail(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.CreateGuardrailRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_guardrail_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_guardrail), "__call__") as call: + call.return_value = gcc_guardrail.Guardrail() + client.update_guardrail(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.UpdateGuardrailRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_guardrail_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_guardrail), "__call__") as call: + call.return_value = None + client.delete_guardrail(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.DeleteGuardrailRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_deployments_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_deployments), "__call__") as call: + call.return_value = agent_service.ListDeploymentsResponse() + client.list_deployments(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.ListDeploymentsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_deployment_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_deployment), "__call__") as call: + call.return_value = deployment.Deployment() + client.get_deployment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.GetDeploymentRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_deployment_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_deployment), "__call__" + ) as call: + call.return_value = gcc_deployment.Deployment() + client.create_deployment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.CreateDeploymentRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_deployment_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_deployment), "__call__" + ) as call: + call.return_value = gcc_deployment.Deployment() + client.update_deployment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.UpdateDeploymentRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_deployment_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_deployment), "__call__" + ) as call: + call.return_value = None + client.delete_deployment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.DeleteDeploymentRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_toolsets_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_toolsets), "__call__") as call: + call.return_value = agent_service.ListToolsetsResponse() + client.list_toolsets(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.ListToolsetsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_toolset_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_toolset), "__call__") as call: + call.return_value = toolset.Toolset() + client.get_toolset(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.GetToolsetRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_toolset_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_toolset), "__call__") as call: + call.return_value = gcc_toolset.Toolset() + client.create_toolset(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.CreateToolsetRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_toolset_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_toolset), "__call__") as call: + call.return_value = gcc_toolset.Toolset() + client.update_toolset(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.UpdateToolsetRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_toolset_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_toolset), "__call__") as call: + call.return_value = None + client.delete_toolset(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.DeleteToolsetRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_app_versions_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_app_versions), "__call__" + ) as call: + call.return_value = agent_service.ListAppVersionsResponse() + client.list_app_versions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.ListAppVersionsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_app_version_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_app_version), "__call__") as call: + call.return_value = app_version.AppVersion() + client.get_app_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.GetAppVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_app_version_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_app_version), "__call__" + ) as call: + call.return_value = gcc_app_version.AppVersion() + client.create_app_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.CreateAppVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_app_version_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_app_version), "__call__" + ) as call: + call.return_value = None + client.delete_app_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.DeleteAppVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_restore_app_version_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.restore_app_version), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.restore_app_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.RestoreAppVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_changelogs_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_changelogs), "__call__") as call: + call.return_value = agent_service.ListChangelogsResponse() + client.list_changelogs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.ListChangelogsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_changelog_empty_call_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_changelog), "__call__") as call: + call.return_value = changelog.Changelog() + client.get_changelog(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.GetChangelogRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = AgentServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_apps_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_apps), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent_service.ListAppsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_apps(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.ListAppsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_app_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_app), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + app.App( + name="name_value", + display_name="display_name_value", + description="description_value", + pinned=True, + root_agent="root_agent_value", + tool_execution_mode=app.App.ToolExecutionMode.PARALLEL, + global_instruction="global_instruction_value", + guardrails=["guardrails_value"], + etag="etag_value", + deployment_count=1737, + locked=True, + ) + ) + await client.get_app(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.GetAppRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_app_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_app), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_app(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.CreateAppRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_app_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_app), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_app.App( + name="name_value", + display_name="display_name_value", + description="description_value", + pinned=True, + root_agent="root_agent_value", + tool_execution_mode=gcc_app.App.ToolExecutionMode.PARALLEL, + global_instruction="global_instruction_value", + guardrails=["guardrails_value"], + etag="etag_value", + deployment_count=1737, + locked=True, + ) + ) + await client.update_app(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.UpdateAppRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_app_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_app), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_app(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.DeleteAppRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_export_app_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.export_app), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.export_app(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.ExportAppRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_import_app_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.import_app), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.import_app(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.ImportAppRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_agents_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_agents), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent_service.ListAgentsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_agents(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.ListAgentsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_agent_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_agent), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent.Agent( + name="name_value", + display_name="display_name_value", + description="description_value", + instruction="instruction_value", + tools=["tools_value"], + child_agents=["child_agents_value"], + guardrails=["guardrails_value"], + etag="etag_value", + generated_summary="generated_summary_value", + ) + ) + await client.get_agent(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.GetAgentRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_agent_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_agent), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_agent.Agent( + name="name_value", + display_name="display_name_value", + description="description_value", + instruction="instruction_value", + tools=["tools_value"], + child_agents=["child_agents_value"], + guardrails=["guardrails_value"], + etag="etag_value", + generated_summary="generated_summary_value", + ) + ) + await client.create_agent(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.CreateAgentRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_agent_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_agent), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_agent.Agent( + name="name_value", + display_name="display_name_value", + description="description_value", + instruction="instruction_value", + tools=["tools_value"], + child_agents=["child_agents_value"], + guardrails=["guardrails_value"], + etag="etag_value", + generated_summary="generated_summary_value", + ) + ) + await client.update_agent(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.UpdateAgentRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_agent_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_agent), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_agent(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.DeleteAgentRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_examples_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_examples), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent_service.ListExamplesResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_examples(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.ListExamplesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_example_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_example), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + example.Example( + name="name_value", + display_name="display_name_value", + description="description_value", + entry_agent="entry_agent_value", + invalid=True, + etag="etag_value", + ) + ) + await client.get_example(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.GetExampleRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_example_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_example), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_example.Example( + name="name_value", + display_name="display_name_value", + description="description_value", + entry_agent="entry_agent_value", + invalid=True, + etag="etag_value", + ) + ) + await client.create_example(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.CreateExampleRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_example_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_example), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_example.Example( + name="name_value", + display_name="display_name_value", + description="description_value", + entry_agent="entry_agent_value", + invalid=True, + etag="etag_value", + ) + ) + await client.update_example(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.UpdateExampleRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_example_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_example), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_example(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.DeleteExampleRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_tools_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_tools), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent_service.ListToolsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_tools(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.ListToolsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_tool_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + tool.Tool( + name="name_value", + display_name="display_name_value", + execution_type=common.ExecutionType.SYNCHRONOUS, + etag="etag_value", + generated_summary="generated_summary_value", + ) + ) + await client.get_tool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.GetToolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_conversations_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent_service.ListConversationsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_conversations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.ListConversationsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_conversation_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_conversation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + conversation.Conversation( + name="name_value", + turn_count=1105, + channel_type=conversation.Conversation.ChannelType.TEXT, + source=conversation.Conversation.Source.LIVE, + input_types=[conversation.Conversation.InputType.INPUT_TYPE_TEXT], + entry_agent="entry_agent_value", + deployment="deployment_value", + app_version="app_version_value", + language_code="language_code_value", + ) + ) + await client.get_conversation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.GetConversationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_conversation_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_conversation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.DeleteConversationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_batch_delete_conversations_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_conversations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.batch_delete_conversations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.BatchDeleteConversationsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_tool_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_tool.Tool( + name="name_value", + display_name="display_name_value", + execution_type=common.ExecutionType.SYNCHRONOUS, + etag="etag_value", + generated_summary="generated_summary_value", + ) + ) + await client.create_tool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.CreateToolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_tool_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_tool.Tool( + name="name_value", + display_name="display_name_value", + execution_type=common.ExecutionType.SYNCHRONOUS, + etag="etag_value", + generated_summary="generated_summary_value", + ) + ) + await client.update_tool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.UpdateToolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_tool_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_tool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.DeleteToolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_guardrails_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_guardrails), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent_service.ListGuardrailsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_guardrails(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.ListGuardrailsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_guardrail_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_guardrail), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + guardrail.Guardrail( + name="name_value", + display_name="display_name_value", + description="description_value", + enabled=True, + etag="etag_value", + ) + ) + await client.get_guardrail(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.GetGuardrailRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_guardrail_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_guardrail), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_guardrail.Guardrail( + name="name_value", + display_name="display_name_value", + description="description_value", + enabled=True, + etag="etag_value", + ) + ) + await client.create_guardrail(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.CreateGuardrailRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_guardrail_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_guardrail), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_guardrail.Guardrail( + name="name_value", + display_name="display_name_value", + description="description_value", + enabled=True, + etag="etag_value", + ) + ) + await client.update_guardrail(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.UpdateGuardrailRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_guardrail_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_guardrail), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_guardrail(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.DeleteGuardrailRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_deployments_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_deployments), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent_service.ListDeploymentsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_deployments(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.ListDeploymentsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_deployment_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_deployment), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + deployment.Deployment( + name="name_value", + display_name="display_name_value", + app_version="app_version_value", + etag="etag_value", + ) + ) + await client.get_deployment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.GetDeploymentRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_deployment_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_deployment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_deployment.Deployment( + name="name_value", + display_name="display_name_value", + app_version="app_version_value", + etag="etag_value", + ) + ) + await client.create_deployment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.CreateDeploymentRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_deployment_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_deployment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_deployment.Deployment( + name="name_value", + display_name="display_name_value", + app_version="app_version_value", + etag="etag_value", + ) + ) + await client.update_deployment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.UpdateDeploymentRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_deployment_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_deployment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_deployment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.DeleteDeploymentRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_toolsets_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_toolsets), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent_service.ListToolsetsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_toolsets(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.ListToolsetsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_toolset_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_toolset), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + toolset.Toolset( + name="name_value", + display_name="display_name_value", + description="description_value", + etag="etag_value", + execution_type=common.ExecutionType.SYNCHRONOUS, + ) + ) + await client.get_toolset(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.GetToolsetRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_toolset_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_toolset), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_toolset.Toolset( + name="name_value", + display_name="display_name_value", + description="description_value", + etag="etag_value", + execution_type=common.ExecutionType.SYNCHRONOUS, + ) + ) + await client.create_toolset(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.CreateToolsetRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_toolset_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_toolset), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_toolset.Toolset( + name="name_value", + display_name="display_name_value", + description="description_value", + etag="etag_value", + execution_type=common.ExecutionType.SYNCHRONOUS, + ) + ) + await client.update_toolset(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.UpdateToolsetRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_toolset_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_toolset), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_toolset(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.DeleteToolsetRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_app_versions_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_app_versions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent_service.ListAppVersionsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_app_versions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.ListAppVersionsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_app_version_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_app_version), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + app_version.AppVersion( + name="name_value", + display_name="display_name_value", + description="description_value", + creator="creator_value", + etag="etag_value", + ) + ) + await client.get_app_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.GetAppVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_app_version_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_app_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_app_version.AppVersion( + name="name_value", + display_name="display_name_value", + description="description_value", + creator="creator_value", + etag="etag_value", + ) + ) + await client.create_app_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.CreateAppVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_app_version_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_app_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_app_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.DeleteAppVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_restore_app_version_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.restore_app_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.restore_app_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.RestoreAppVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_changelogs_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_changelogs), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + agent_service.ListChangelogsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_changelogs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.ListChangelogsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_changelog_empty_call_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_changelog), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + changelog.Changelog( + name="name_value", + author="author_value", + display_name="display_name_value", + description="description_value", + resource="resource_value", + resource_type="resource_type_value", + action="action_value", + sequence_number=1601, + ) + ) + await client.get_changelog(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.GetChangelogRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = AgentServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_apps_rest_bad_request(request_type=agent_service.ListAppsRequest): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_apps(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.ListAppsRequest, + dict, + ], +) +def test_list_apps_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = agent_service.ListAppsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = agent_service.ListAppsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_apps(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAppsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_apps_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_list_apps" + ) as post, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_list_apps_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_list_apps" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.ListAppsRequest.pb(agent_service.ListAppsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = agent_service.ListAppsResponse.to_json( + agent_service.ListAppsResponse() + ) + req.return_value.content = return_value + + request = agent_service.ListAppsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = agent_service.ListAppsResponse() + post_with_metadata.return_value = agent_service.ListAppsResponse(), metadata + + client.list_apps( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_app_rest_bad_request(request_type=agent_service.GetAppRequest): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_app(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.GetAppRequest, + dict, + ], +) +def test_get_app_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = app.App( + name="name_value", + display_name="display_name_value", + description="description_value", + pinned=True, + root_agent="root_agent_value", + tool_execution_mode=app.App.ToolExecutionMode.PARALLEL, + global_instruction="global_instruction_value", + guardrails=["guardrails_value"], + etag="etag_value", + deployment_count=1737, + locked=True, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = app.App.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_app(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, app.App) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.pinned is True + assert response.root_agent == "root_agent_value" + assert response.tool_execution_mode == app.App.ToolExecutionMode.PARALLEL + assert response.global_instruction == "global_instruction_value" + assert response.guardrails == ["guardrails_value"] + assert response.etag == "etag_value" + assert response.deployment_count == 1737 + assert response.locked is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_app_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_get_app" + ) as post, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_get_app_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_get_app" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.GetAppRequest.pb(agent_service.GetAppRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = app.App.to_json(app.App()) + req.return_value.content = return_value + + request = agent_service.GetAppRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = app.App() + post_with_metadata.return_value = app.App(), metadata + + client.get_app( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_app_rest_bad_request(request_type=agent_service.CreateAppRequest): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_app(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.CreateAppRequest, + dict, + ], +) +def test_create_app_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["app"] = { + "name": "name_value", + "display_name": "display_name_value", + "description": "description_value", + "pinned": True, + "root_agent": "root_agent_value", + "language_settings": { + "default_language_code": "default_language_code_value", + "supported_language_codes": [ + "supported_language_codes_value1", + "supported_language_codes_value2", + ], + "enable_multilingual_support": True, + "fallback_action": "fallback_action_value", + }, + "time_zone_settings": {"time_zone": "time_zone_value"}, + "audio_processing_config": { + "synthesize_speech_configs": {}, + "barge_in_config": {"disable_barge_in": True, "barge_in_awareness": True}, + "inactivity_timeout": {"seconds": 751, "nanos": 543}, + "ambient_sound_config": { + "prebuilt_ambient_noise": 1, + "gcs_uri": "gcs_uri_value", + "prebuilt_ambient_sound": "prebuilt_ambient_sound_value", + "volume_gain_db": 0.1467, + }, + }, + "logging_settings": { + "redaction_config": { + "enable_redaction": True, + "inspect_template": "inspect_template_value", + "deidentify_template": "deidentify_template_value", + }, + "audio_recording_config": { + "gcs_bucket": "gcs_bucket_value", + "gcs_path_prefix": "gcs_path_prefix_value", + }, + "bigquery_export_settings": { + "enabled": True, + "project": "project_value", + "dataset": "dataset_value", + }, + "cloud_logging_settings": {"enable_cloud_logging": True}, + "conversation_logging_settings": {"disable_conversation_logging": True}, + "evaluation_audio_recording_config": {}, + "metric_analysis_settings": {"llm_metrics_opted_out": True}, + }, + "error_handling_settings": {"error_handling_strategy": 1}, + "model_settings": {"model": "model_value", "temperature": 0.1198}, + "tool_execution_mode": 1, + "evaluation_metrics_thresholds": { + "golden_evaluation_metrics_thresholds": { + "turn_level_metrics_thresholds": { + "semantic_similarity_success_threshold": 3966, + "overall_tool_invocation_correctness_threshold": 0.4833, + "semantic_similarity_channel": 1, + }, + "expectation_level_metrics_thresholds": { + "tool_invocation_parameter_correctness_threshold": 0.5037 + }, + "tool_matching_settings": {"extra_tool_call_behavior": 1}, + }, + "hallucination_metric_behavior": 1, + "golden_hallucination_metric_behavior": 1, + "scenario_hallucination_metric_behavior": 1, + }, + "variable_declarations": [ + { + "name": "name_value", + "description": "description_value", + "schema": { + "type_": 1, + "properties": {}, + "required": ["required_value1", "required_value2"], + "description": "description_value", + "items": {}, + "nullable": True, + "unique_items": True, + "prefix_items": {}, + "additional_properties": {}, + "any_of": {}, + "enum": ["enum_value1", "enum_value2"], + "default": { + "null_value": 0, + "number_value": 0.1285, + "string_value": "string_value_value", + "bool_value": True, + "struct_value": {"fields": {}}, + "list_value": {"values": {}}, + }, + "ref": "ref_value", + "defs": {}, + "title": "title_value", + "min_items": 965, + "max_items": 967, + "minimum": 0.764, + "maximum": 0.766, + }, + } + ], + "predefined_variable_declarations": {}, + "global_instruction": "global_instruction_value", + "guardrails": ["guardrails_value1", "guardrails_value2"], + "data_store_settings": {"engines": [{"name": "name_value", "type_": 1}]}, + "default_channel_profile": { + "profile_id": "profile_id_value", + "channel_type": 2, + "persona_property": {"persona": 1}, + "disable_dtmf": True, + "disable_barge_in_control": True, + "web_widget_config": { + "modality": 1, + "theme": 1, + "web_widget_title": "web_widget_title_value", + "security_settings": { + "enable_public_access": True, + "enable_origin_check": True, + "allowed_origins": [ + "allowed_origins_value1", + "allowed_origins_value2", + ], + "enable_recaptcha": True, + }, + }, + "noise_suppression_level": "noise_suppression_level_value", + }, + "metadata": {}, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "etag": "etag_value", + "deployment_count": 1737, + "client_certificate_settings": { + "tls_certificate": "tls_certificate_value", + "private_key": "private_key_value", + "passphrase": "passphrase_value", + }, + "locked": True, + "evaluation_personas": [ + { + "name": "name_value", + "description": "description_value", + "display_name": "display_name_value", + "personality": "personality_value", + "speech_config": { + "speaking_rate": 0.1373, + "environment": 3, + "voice_id": "voice_id_value", + }, + } + ], + "evaluation_settings": { + "scenario_conversation_initiator": 1, + "golden_run_method": 1, + "golden_evaluation_tool_call_behaviour": 1, + "scenario_evaluation_tool_call_behaviour": 1, + }, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = agent_service.CreateAppRequest.meta.fields["app"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["app"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["app"][field])): + del request_init["app"][field][i][subfield] + else: + del request_init["app"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_app(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_app_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.AgentServiceRestInterceptor, "post_create_app" + ) as post, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_create_app_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_create_app" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.CreateAppRequest.pb(agent_service.CreateAppRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = agent_service.CreateAppRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.create_app( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_app_rest_bad_request(request_type=agent_service.UpdateAppRequest): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"app": {"name": "projects/sample1/locations/sample2/apps/sample3"}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_app(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.UpdateAppRequest, + dict, + ], +) +def test_update_app_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"app": {"name": "projects/sample1/locations/sample2/apps/sample3"}} + request_init["app"] = { + "name": "projects/sample1/locations/sample2/apps/sample3", + "display_name": "display_name_value", + "description": "description_value", + "pinned": True, + "root_agent": "root_agent_value", + "language_settings": { + "default_language_code": "default_language_code_value", + "supported_language_codes": [ + "supported_language_codes_value1", + "supported_language_codes_value2", + ], + "enable_multilingual_support": True, + "fallback_action": "fallback_action_value", + }, + "time_zone_settings": {"time_zone": "time_zone_value"}, + "audio_processing_config": { + "synthesize_speech_configs": {}, + "barge_in_config": {"disable_barge_in": True, "barge_in_awareness": True}, + "inactivity_timeout": {"seconds": 751, "nanos": 543}, + "ambient_sound_config": { + "prebuilt_ambient_noise": 1, + "gcs_uri": "gcs_uri_value", + "prebuilt_ambient_sound": "prebuilt_ambient_sound_value", + "volume_gain_db": 0.1467, + }, + }, + "logging_settings": { + "redaction_config": { + "enable_redaction": True, + "inspect_template": "inspect_template_value", + "deidentify_template": "deidentify_template_value", + }, + "audio_recording_config": { + "gcs_bucket": "gcs_bucket_value", + "gcs_path_prefix": "gcs_path_prefix_value", + }, + "bigquery_export_settings": { + "enabled": True, + "project": "project_value", + "dataset": "dataset_value", + }, + "cloud_logging_settings": {"enable_cloud_logging": True}, + "conversation_logging_settings": {"disable_conversation_logging": True}, + "evaluation_audio_recording_config": {}, + "metric_analysis_settings": {"llm_metrics_opted_out": True}, + }, + "error_handling_settings": {"error_handling_strategy": 1}, + "model_settings": {"model": "model_value", "temperature": 0.1198}, + "tool_execution_mode": 1, + "evaluation_metrics_thresholds": { + "golden_evaluation_metrics_thresholds": { + "turn_level_metrics_thresholds": { + "semantic_similarity_success_threshold": 3966, + "overall_tool_invocation_correctness_threshold": 0.4833, + "semantic_similarity_channel": 1, + }, + "expectation_level_metrics_thresholds": { + "tool_invocation_parameter_correctness_threshold": 0.5037 + }, + "tool_matching_settings": {"extra_tool_call_behavior": 1}, + }, + "hallucination_metric_behavior": 1, + "golden_hallucination_metric_behavior": 1, + "scenario_hallucination_metric_behavior": 1, + }, + "variable_declarations": [ + { + "name": "name_value", + "description": "description_value", + "schema": { + "type_": 1, + "properties": {}, + "required": ["required_value1", "required_value2"], + "description": "description_value", + "items": {}, + "nullable": True, + "unique_items": True, + "prefix_items": {}, + "additional_properties": {}, + "any_of": {}, + "enum": ["enum_value1", "enum_value2"], + "default": { + "null_value": 0, + "number_value": 0.1285, + "string_value": "string_value_value", + "bool_value": True, + "struct_value": {"fields": {}}, + "list_value": {"values": {}}, + }, + "ref": "ref_value", + "defs": {}, + "title": "title_value", + "min_items": 965, + "max_items": 967, + "minimum": 0.764, + "maximum": 0.766, + }, + } + ], + "predefined_variable_declarations": {}, + "global_instruction": "global_instruction_value", + "guardrails": ["guardrails_value1", "guardrails_value2"], + "data_store_settings": {"engines": [{"name": "name_value", "type_": 1}]}, + "default_channel_profile": { + "profile_id": "profile_id_value", + "channel_type": 2, + "persona_property": {"persona": 1}, + "disable_dtmf": True, + "disable_barge_in_control": True, + "web_widget_config": { + "modality": 1, + "theme": 1, + "web_widget_title": "web_widget_title_value", + "security_settings": { + "enable_public_access": True, + "enable_origin_check": True, + "allowed_origins": [ + "allowed_origins_value1", + "allowed_origins_value2", + ], + "enable_recaptcha": True, + }, + }, + "noise_suppression_level": "noise_suppression_level_value", + }, + "metadata": {}, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "etag": "etag_value", + "deployment_count": 1737, + "client_certificate_settings": { + "tls_certificate": "tls_certificate_value", + "private_key": "private_key_value", + "passphrase": "passphrase_value", + }, + "locked": True, + "evaluation_personas": [ + { + "name": "name_value", + "description": "description_value", + "display_name": "display_name_value", + "personality": "personality_value", + "speech_config": { + "speaking_rate": 0.1373, + "environment": 3, + "voice_id": "voice_id_value", + }, + } + ], + "evaluation_settings": { + "scenario_conversation_initiator": 1, + "golden_run_method": 1, + "golden_evaluation_tool_call_behaviour": 1, + "scenario_evaluation_tool_call_behaviour": 1, + }, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = agent_service.UpdateAppRequest.meta.fields["app"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["app"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["app"][field])): + del request_init["app"][field][i][subfield] + else: + del request_init["app"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcc_app.App( + name="name_value", + display_name="display_name_value", + description="description_value", + pinned=True, + root_agent="root_agent_value", + tool_execution_mode=gcc_app.App.ToolExecutionMode.PARALLEL, + global_instruction="global_instruction_value", + guardrails=["guardrails_value"], + etag="etag_value", + deployment_count=1737, + locked=True, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcc_app.App.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_app(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_app.App) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.pinned is True + assert response.root_agent == "root_agent_value" + assert response.tool_execution_mode == gcc_app.App.ToolExecutionMode.PARALLEL + assert response.global_instruction == "global_instruction_value" + assert response.guardrails == ["guardrails_value"] + assert response.etag == "etag_value" + assert response.deployment_count == 1737 + assert response.locked is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_app_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_update_app" + ) as post, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_update_app_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_update_app" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.UpdateAppRequest.pb(agent_service.UpdateAppRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gcc_app.App.to_json(gcc_app.App()) + req.return_value.content = return_value + + request = agent_service.UpdateAppRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcc_app.App() + post_with_metadata.return_value = gcc_app.App(), metadata + + client.update_app( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_app_rest_bad_request(request_type=agent_service.DeleteAppRequest): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_app(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.DeleteAppRequest, + dict, + ], +) +def test_delete_app_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_app(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_app_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.AgentServiceRestInterceptor, "post_delete_app" + ) as post, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_delete_app_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_delete_app" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.DeleteAppRequest.pb(agent_service.DeleteAppRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = agent_service.DeleteAppRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_app( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_export_app_rest_bad_request(request_type=agent_service.ExportAppRequest): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.export_app(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.ExportAppRequest, + dict, + ], +) +def test_export_app_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.export_app(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_export_app_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.AgentServiceRestInterceptor, "post_export_app" + ) as post, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_export_app_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_export_app" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.ExportAppRequest.pb(agent_service.ExportAppRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = agent_service.ExportAppRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.export_app( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_import_app_rest_bad_request(request_type=agent_service.ImportAppRequest): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.import_app(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.ImportAppRequest, + dict, + ], +) +def test_import_app_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.import_app(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_import_app_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.AgentServiceRestInterceptor, "post_import_app" + ) as post, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_import_app_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_import_app" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.ImportAppRequest.pb(agent_service.ImportAppRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = agent_service.ImportAppRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.import_app( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_agents_rest_bad_request(request_type=agent_service.ListAgentsRequest): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_agents(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.ListAgentsRequest, + dict, + ], +) +def test_list_agents_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = agent_service.ListAgentsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = agent_service.ListAgentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_agents(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAgentsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_agents_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_list_agents" + ) as post, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_list_agents_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_list_agents" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.ListAgentsRequest.pb( + agent_service.ListAgentsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = agent_service.ListAgentsResponse.to_json( + agent_service.ListAgentsResponse() + ) + req.return_value.content = return_value + + request = agent_service.ListAgentsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = agent_service.ListAgentsResponse() + post_with_metadata.return_value = agent_service.ListAgentsResponse(), metadata + + client.list_agents( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_agent_rest_bad_request(request_type=agent_service.GetAgentRequest): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/agents/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_agent(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.GetAgentRequest, + dict, + ], +) +def test_get_agent_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/agents/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = agent.Agent( + name="name_value", + display_name="display_name_value", + description="description_value", + instruction="instruction_value", + tools=["tools_value"], + child_agents=["child_agents_value"], + guardrails=["guardrails_value"], + etag="etag_value", + generated_summary="generated_summary_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = agent.Agent.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_agent(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, agent.Agent) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.instruction == "instruction_value" + assert response.tools == ["tools_value"] + assert response.child_agents == ["child_agents_value"] + assert response.guardrails == ["guardrails_value"] + assert response.etag == "etag_value" + assert response.generated_summary == "generated_summary_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_agent_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_get_agent" + ) as post, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_get_agent_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_get_agent" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.GetAgentRequest.pb(agent_service.GetAgentRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = agent.Agent.to_json(agent.Agent()) + req.return_value.content = return_value + + request = agent_service.GetAgentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = agent.Agent() + post_with_metadata.return_value = agent.Agent(), metadata + + client.get_agent( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_agent_rest_bad_request(request_type=agent_service.CreateAgentRequest): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_agent(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.CreateAgentRequest, + dict, + ], +) +def test_create_agent_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request_init["agent"] = { + "llm_agent": {}, + "remote_dialogflow_agent": { + "agent": "agent_value", + "flow_id": "flow_id_value", + "environment_id": "environment_id_value", + "input_variable_mapping": {}, + "output_variable_mapping": {}, + "respect_response_interruption_settings": True, + }, + "name": "name_value", + "display_name": "display_name_value", + "description": "description_value", + "model_settings": {"model": "model_value", "temperature": 0.1198}, + "instruction": "instruction_value", + "tools": ["tools_value1", "tools_value2"], + "child_agents": ["child_agents_value1", "child_agents_value2"], + "before_agent_callbacks": [ + { + "python_code": "python_code_value", + "description": "description_value", + "disabled": True, + "proactive_execution_enabled": True, + } + ], + "after_agent_callbacks": {}, + "before_model_callbacks": {}, + "after_model_callbacks": {}, + "before_tool_callbacks": {}, + "after_tool_callbacks": {}, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "guardrails": ["guardrails_value1", "guardrails_value2"], + "etag": "etag_value", + "toolsets": [ + { + "toolset": "toolset_value", + "tool_ids": ["tool_ids_value1", "tool_ids_value2"], + } + ], + "generated_summary": "generated_summary_value", + "transfer_rules": [ + { + "deterministic_transfer": { + "expression_condition": {"expression": "expression_value"}, + "python_code_condition": {"python_code": "python_code_value"}, + }, + "disable_planner_transfer": {"expression_condition": {}}, + "child_agent": "child_agent_value", + "direction": 1, + } + ], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = agent_service.CreateAgentRequest.meta.fields["agent"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["agent"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["agent"][field])): + del request_init["agent"][field][i][subfield] + else: + del request_init["agent"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcc_agent.Agent( + name="name_value", + display_name="display_name_value", + description="description_value", + instruction="instruction_value", + tools=["tools_value"], + child_agents=["child_agents_value"], + guardrails=["guardrails_value"], + etag="etag_value", + generated_summary="generated_summary_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcc_agent.Agent.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_agent(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_agent.Agent) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.instruction == "instruction_value" + assert response.tools == ["tools_value"] + assert response.child_agents == ["child_agents_value"] + assert response.guardrails == ["guardrails_value"] + assert response.etag == "etag_value" + assert response.generated_summary == "generated_summary_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_agent_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_create_agent" + ) as post, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_create_agent_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_create_agent" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.CreateAgentRequest.pb( + agent_service.CreateAgentRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gcc_agent.Agent.to_json(gcc_agent.Agent()) + req.return_value.content = return_value + + request = agent_service.CreateAgentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcc_agent.Agent() + post_with_metadata.return_value = gcc_agent.Agent(), metadata + + client.create_agent( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_agent_rest_bad_request(request_type=agent_service.UpdateAgentRequest): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "agent": { + "name": "projects/sample1/locations/sample2/apps/sample3/agents/sample4" + } + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_agent(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.UpdateAgentRequest, + dict, + ], +) +def test_update_agent_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "agent": { + "name": "projects/sample1/locations/sample2/apps/sample3/agents/sample4" + } + } + request_init["agent"] = { + "llm_agent": {}, + "remote_dialogflow_agent": { + "agent": "agent_value", + "flow_id": "flow_id_value", + "environment_id": "environment_id_value", + "input_variable_mapping": {}, + "output_variable_mapping": {}, + "respect_response_interruption_settings": True, + }, + "name": "projects/sample1/locations/sample2/apps/sample3/agents/sample4", + "display_name": "display_name_value", + "description": "description_value", + "model_settings": {"model": "model_value", "temperature": 0.1198}, + "instruction": "instruction_value", + "tools": ["tools_value1", "tools_value2"], + "child_agents": ["child_agents_value1", "child_agents_value2"], + "before_agent_callbacks": [ + { + "python_code": "python_code_value", + "description": "description_value", + "disabled": True, + "proactive_execution_enabled": True, + } + ], + "after_agent_callbacks": {}, + "before_model_callbacks": {}, + "after_model_callbacks": {}, + "before_tool_callbacks": {}, + "after_tool_callbacks": {}, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "guardrails": ["guardrails_value1", "guardrails_value2"], + "etag": "etag_value", + "toolsets": [ + { + "toolset": "toolset_value", + "tool_ids": ["tool_ids_value1", "tool_ids_value2"], + } + ], + "generated_summary": "generated_summary_value", + "transfer_rules": [ + { + "deterministic_transfer": { + "expression_condition": {"expression": "expression_value"}, + "python_code_condition": {"python_code": "python_code_value"}, + }, + "disable_planner_transfer": {"expression_condition": {}}, + "child_agent": "child_agent_value", + "direction": 1, + } + ], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = agent_service.UpdateAgentRequest.meta.fields["agent"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["agent"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["agent"][field])): + del request_init["agent"][field][i][subfield] + else: + del request_init["agent"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcc_agent.Agent( + name="name_value", + display_name="display_name_value", + description="description_value", + instruction="instruction_value", + tools=["tools_value"], + child_agents=["child_agents_value"], + guardrails=["guardrails_value"], + etag="etag_value", + generated_summary="generated_summary_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcc_agent.Agent.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_agent(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_agent.Agent) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.instruction == "instruction_value" + assert response.tools == ["tools_value"] + assert response.child_agents == ["child_agents_value"] + assert response.guardrails == ["guardrails_value"] + assert response.etag == "etag_value" + assert response.generated_summary == "generated_summary_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_agent_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_update_agent" + ) as post, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_update_agent_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_update_agent" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.UpdateAgentRequest.pb( + agent_service.UpdateAgentRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gcc_agent.Agent.to_json(gcc_agent.Agent()) + req.return_value.content = return_value + + request = agent_service.UpdateAgentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcc_agent.Agent() + post_with_metadata.return_value = gcc_agent.Agent(), metadata + + client.update_agent( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_agent_rest_bad_request(request_type=agent_service.DeleteAgentRequest): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/agents/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_agent(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.DeleteAgentRequest, + dict, + ], +) +def test_delete_agent_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/agents/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_agent(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_agent_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_delete_agent" + ) as pre: + pre.assert_not_called() + pb_message = agent_service.DeleteAgentRequest.pb( + agent_service.DeleteAgentRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = agent_service.DeleteAgentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_agent( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_list_examples_rest_bad_request(request_type=agent_service.ListExamplesRequest): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_examples(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.ListExamplesRequest, + dict, + ], +) +def test_list_examples_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = agent_service.ListExamplesResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = agent_service.ListExamplesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_examples(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListExamplesPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_examples_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_list_examples" + ) as post, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_list_examples_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_list_examples" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.ListExamplesRequest.pb( + agent_service.ListExamplesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = agent_service.ListExamplesResponse.to_json( + agent_service.ListExamplesResponse() + ) + req.return_value.content = return_value + + request = agent_service.ListExamplesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = agent_service.ListExamplesResponse() + post_with_metadata.return_value = agent_service.ListExamplesResponse(), metadata + + client.list_examples( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_example_rest_bad_request(request_type=agent_service.GetExampleRequest): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/examples/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_example(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.GetExampleRequest, + dict, + ], +) +def test_get_example_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/examples/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = example.Example( + name="name_value", + display_name="display_name_value", + description="description_value", + entry_agent="entry_agent_value", + invalid=True, + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = example.Example.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_example(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, example.Example) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.entry_agent == "entry_agent_value" + assert response.invalid is True + assert response.etag == "etag_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_example_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_get_example" + ) as post, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_get_example_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_get_example" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.GetExampleRequest.pb( + agent_service.GetExampleRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = example.Example.to_json(example.Example()) + req.return_value.content = return_value + + request = agent_service.GetExampleRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = example.Example() + post_with_metadata.return_value = example.Example(), metadata + + client.get_example( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_example_rest_bad_request( + request_type=agent_service.CreateExampleRequest, +): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_example(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.CreateExampleRequest, + dict, + ], +) +def test_create_example_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request_init["example"] = { + "name": "name_value", + "display_name": "display_name_value", + "description": "description_value", + "entry_agent": "entry_agent_value", + "messages": [ + { + "role": "role_value", + "chunks": [ + { + "text": "text_value", + "transcript": "transcript_value", + "blob": {"mime_type": "mime_type_value", "data": b"data_blob"}, + "payload": {"fields": {}}, + "image": {"mime_type": "mime_type_value", "data": b"data_blob"}, + "tool_call": { + "tool": "tool_value", + "toolset_tool": { + "toolset": "toolset_value", + "tool_id": "tool_id_value", + }, + "id": "id_value", + "display_name": "display_name_value", + "args": {}, + }, + "tool_response": { + "tool": "tool_value", + "toolset_tool": {}, + "id": "id_value", + "display_name": "display_name_value", + "response": {}, + }, + "agent_transfer": { + "target_agent": "target_agent_value", + "display_name": "display_name_value", + }, + "updated_variables": {}, + "default_variables": {}, + } + ], + "event_time": {"seconds": 751, "nanos": 543}, + } + ], + "create_time": {}, + "update_time": {}, + "invalid": True, + "etag": "etag_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = agent_service.CreateExampleRequest.meta.fields["example"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["example"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["example"][field])): + del request_init["example"][field][i][subfield] + else: + del request_init["example"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcc_example.Example( + name="name_value", + display_name="display_name_value", + description="description_value", + entry_agent="entry_agent_value", + invalid=True, + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcc_example.Example.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_example(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_example.Example) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.entry_agent == "entry_agent_value" + assert response.invalid is True + assert response.etag == "etag_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_example_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_create_example" + ) as post, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_create_example_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_create_example" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.CreateExampleRequest.pb( + agent_service.CreateExampleRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gcc_example.Example.to_json(gcc_example.Example()) + req.return_value.content = return_value + + request = agent_service.CreateExampleRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcc_example.Example() + post_with_metadata.return_value = gcc_example.Example(), metadata + + client.create_example( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_example_rest_bad_request( + request_type=agent_service.UpdateExampleRequest, +): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "example": { + "name": "projects/sample1/locations/sample2/apps/sample3/examples/sample4" + } + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_example(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.UpdateExampleRequest, + dict, + ], +) +def test_update_example_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "example": { + "name": "projects/sample1/locations/sample2/apps/sample3/examples/sample4" + } + } + request_init["example"] = { + "name": "projects/sample1/locations/sample2/apps/sample3/examples/sample4", + "display_name": "display_name_value", + "description": "description_value", + "entry_agent": "entry_agent_value", + "messages": [ + { + "role": "role_value", + "chunks": [ + { + "text": "text_value", + "transcript": "transcript_value", + "blob": {"mime_type": "mime_type_value", "data": b"data_blob"}, + "payload": {"fields": {}}, + "image": {"mime_type": "mime_type_value", "data": b"data_blob"}, + "tool_call": { + "tool": "tool_value", + "toolset_tool": { + "toolset": "toolset_value", + "tool_id": "tool_id_value", + }, + "id": "id_value", + "display_name": "display_name_value", + "args": {}, + }, + "tool_response": { + "tool": "tool_value", + "toolset_tool": {}, + "id": "id_value", + "display_name": "display_name_value", + "response": {}, + }, + "agent_transfer": { + "target_agent": "target_agent_value", + "display_name": "display_name_value", + }, + "updated_variables": {}, + "default_variables": {}, + } + ], + "event_time": {"seconds": 751, "nanos": 543}, + } + ], + "create_time": {}, + "update_time": {}, + "invalid": True, + "etag": "etag_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = agent_service.UpdateExampleRequest.meta.fields["example"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["example"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["example"][field])): + del request_init["example"][field][i][subfield] + else: + del request_init["example"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcc_example.Example( + name="name_value", + display_name="display_name_value", + description="description_value", + entry_agent="entry_agent_value", + invalid=True, + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcc_example.Example.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_example(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_example.Example) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.entry_agent == "entry_agent_value" + assert response.invalid is True + assert response.etag == "etag_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_example_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_update_example" + ) as post, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_update_example_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_update_example" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.UpdateExampleRequest.pb( + agent_service.UpdateExampleRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gcc_example.Example.to_json(gcc_example.Example()) + req.return_value.content = return_value + + request = agent_service.UpdateExampleRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcc_example.Example() + post_with_metadata.return_value = gcc_example.Example(), metadata + + client.update_example( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_example_rest_bad_request( + request_type=agent_service.DeleteExampleRequest, +): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/examples/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_example(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.DeleteExampleRequest, + dict, + ], +) +def test_delete_example_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/examples/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_example(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_example_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_delete_example" + ) as pre: + pre.assert_not_called() + pb_message = agent_service.DeleteExampleRequest.pb( + agent_service.DeleteExampleRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = agent_service.DeleteExampleRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_example( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_list_tools_rest_bad_request(request_type=agent_service.ListToolsRequest): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_tools(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.ListToolsRequest, + dict, + ], +) +def test_list_tools_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = agent_service.ListToolsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = agent_service.ListToolsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_tools(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListToolsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_tools_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_list_tools" + ) as post, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_list_tools_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_list_tools" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.ListToolsRequest.pb(agent_service.ListToolsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = agent_service.ListToolsResponse.to_json( + agent_service.ListToolsResponse() + ) + req.return_value.content = return_value + + request = agent_service.ListToolsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = agent_service.ListToolsResponse() + post_with_metadata.return_value = agent_service.ListToolsResponse(), metadata + + client.list_tools( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_tool_rest_bad_request(request_type=agent_service.GetToolRequest): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/tools/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_tool(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.GetToolRequest, + dict, + ], +) +def test_get_tool_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/tools/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = tool.Tool( + name="name_value", + display_name="display_name_value", + execution_type=common.ExecutionType.SYNCHRONOUS, + etag="etag_value", + generated_summary="generated_summary_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = tool.Tool.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_tool(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, tool.Tool) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.execution_type == common.ExecutionType.SYNCHRONOUS + assert response.etag == "etag_value" + assert response.generated_summary == "generated_summary_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_tool_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_get_tool" + ) as post, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_get_tool_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_get_tool" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.GetToolRequest.pb(agent_service.GetToolRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = tool.Tool.to_json(tool.Tool()) + req.return_value.content = return_value + + request = agent_service.GetToolRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = tool.Tool() + post_with_metadata.return_value = tool.Tool(), metadata + + client.get_tool( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_conversations_rest_bad_request( + request_type=agent_service.ListConversationsRequest, +): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_conversations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.ListConversationsRequest, + dict, + ], +) +def test_list_conversations_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = agent_service.ListConversationsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = agent_service.ListConversationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_conversations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListConversationsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_conversations_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_list_conversations" + ) as post, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_list_conversations_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_list_conversations" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.ListConversationsRequest.pb( + agent_service.ListConversationsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = agent_service.ListConversationsResponse.to_json( + agent_service.ListConversationsResponse() + ) + req.return_value.content = return_value + + request = agent_service.ListConversationsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = agent_service.ListConversationsResponse() + post_with_metadata.return_value = ( + agent_service.ListConversationsResponse(), + metadata, + ) + + client.list_conversations( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_conversation_rest_bad_request( + request_type=agent_service.GetConversationRequest, +): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/conversations/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_conversation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.GetConversationRequest, + dict, + ], +) +def test_get_conversation_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/conversations/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = conversation.Conversation( + name="name_value", + turn_count=1105, + channel_type=conversation.Conversation.ChannelType.TEXT, + source=conversation.Conversation.Source.LIVE, + input_types=[conversation.Conversation.InputType.INPUT_TYPE_TEXT], + entry_agent="entry_agent_value", + deployment="deployment_value", + app_version="app_version_value", + language_code="language_code_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = conversation.Conversation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_conversation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, conversation.Conversation) + assert response.name == "name_value" + assert response.turn_count == 1105 + assert response.channel_type == conversation.Conversation.ChannelType.TEXT + assert response.source == conversation.Conversation.Source.LIVE + assert response.input_types == [conversation.Conversation.InputType.INPUT_TYPE_TEXT] + assert response.entry_agent == "entry_agent_value" + assert response.deployment == "deployment_value" + assert response.app_version == "app_version_value" + assert response.language_code == "language_code_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_conversation_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_get_conversation" + ) as post, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_get_conversation_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_get_conversation" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.GetConversationRequest.pb( + agent_service.GetConversationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = conversation.Conversation.to_json(conversation.Conversation()) + req.return_value.content = return_value + + request = agent_service.GetConversationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = conversation.Conversation() + post_with_metadata.return_value = conversation.Conversation(), metadata + + client.get_conversation( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_conversation_rest_bad_request( + request_type=agent_service.DeleteConversationRequest, +): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/conversations/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_conversation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.DeleteConversationRequest, + dict, + ], +) +def test_delete_conversation_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/conversations/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_conversation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_conversation_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_delete_conversation" + ) as pre: + pre.assert_not_called() + pb_message = agent_service.DeleteConversationRequest.pb( + agent_service.DeleteConversationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = agent_service.DeleteConversationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_conversation( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_batch_delete_conversations_rest_bad_request( + request_type=agent_service.BatchDeleteConversationsRequest, +): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.batch_delete_conversations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.BatchDeleteConversationsRequest, + dict, + ], +) +def test_batch_delete_conversations_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.batch_delete_conversations(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_delete_conversations_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.AgentServiceRestInterceptor, "post_batch_delete_conversations" + ) as post, mock.patch.object( + transports.AgentServiceRestInterceptor, + "post_batch_delete_conversations_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_batch_delete_conversations" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.BatchDeleteConversationsRequest.pb( + agent_service.BatchDeleteConversationsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = agent_service.BatchDeleteConversationsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.batch_delete_conversations( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_tool_rest_bad_request(request_type=agent_service.CreateToolRequest): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_tool(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.CreateToolRequest, + dict, + ], +) +def test_create_tool_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request_init["tool"] = { + "client_function": { + "name": "name_value", + "description": "description_value", + "parameters": { + "type_": 1, + "properties": {}, + "required": ["required_value1", "required_value2"], + "description": "description_value", + "items": {}, + "nullable": True, + "unique_items": True, + "prefix_items": {}, + "additional_properties": {}, + "any_of": {}, + "enum": ["enum_value1", "enum_value2"], + "default": { + "null_value": 0, + "number_value": 0.1285, + "string_value": "string_value_value", + "bool_value": True, + "struct_value": {"fields": {}}, + "list_value": {"values": {}}, + }, + "ref": "ref_value", + "defs": {}, + "title": "title_value", + "min_items": 965, + "max_items": 967, + "minimum": 0.764, + "maximum": 0.766, + }, + "response": {}, + }, + "open_api_tool": { + "open_api_schema": "open_api_schema_value", + "name": "name_value", + "description": "description_value", + "api_authentication": { + "api_key_config": { + "key_name": "key_name_value", + "api_key_secret_version": "api_key_secret_version_value", + "request_location": 1, + }, + "oauth_config": { + "oauth_grant_type": 1, + "client_id": "client_id_value", + "client_secret_version": "client_secret_version_value", + "token_endpoint": "token_endpoint_value", + "scopes": ["scopes_value1", "scopes_value2"], + }, + "service_agent_id_token_auth_config": {}, + "service_account_auth_config": { + "service_account": "service_account_value", + "scopes": ["scopes_value1", "scopes_value2"], + }, + "bearer_token_config": {"token": "token_value"}, + }, + "tls_config": { + "ca_certs": [ + {"display_name": "display_name_value", "cert": b"cert_blob"} + ] + }, + "service_directory_config": {"service": "service_value"}, + "ignore_unknown_fields_": True, + "url": "url_value", + }, + "google_search_tool": { + "name": "name_value", + "description": "description_value", + "context_urls": ["context_urls_value1", "context_urls_value2"], + "preferred_domains": [ + "preferred_domains_value1", + "preferred_domains_value2", + ], + "exclude_domains": ["exclude_domains_value1", "exclude_domains_value2"], + "prompt_config": { + "text_prompt": "text_prompt_value", + "voice_prompt": "voice_prompt_value", + }, + }, + "connector_tool": { + "connection": "connection_value", + "action": { + "connection_action_id": "connection_action_id_value", + "entity_operation": {"entity_id": "entity_id_value", "operation": 1}, + "input_fields": ["input_fields_value1", "input_fields_value2"], + "output_fields": ["output_fields_value1", "output_fields_value2"], + }, + "auth_config": { + "oauth2_auth_code_config": {"oauth_token": "oauth_token_value"}, + "oauth2_jwt_bearer_config": { + "issuer": "issuer_value", + "subject": "subject_value", + "client_key": "client_key_value", + }, + }, + "name": "name_value", + "description": "description_value", + }, + "data_store_tool": { + "data_store_source": { + "filter": "filter_value", + "data_store": { + "name": "name_value", + "type_": 1, + "document_processing_mode": 1, + "display_name": "display_name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "connector_config": { + "collection": "collection_value", + "collection_display_name": "collection_display_name_value", + "data_source": "data_source_value", + }, + }, + }, + "engine_source": { + "engine": "engine_value", + "data_store_sources": {}, + "filter": "filter_value", + }, + "name": "name_value", + "description": "description_value", + "boost_specs": [ + { + "data_stores": ["data_stores_value1", "data_stores_value2"], + "spec": [ + { + "condition_boost_specs": [ + { + "condition": "condition_value", + "boost": 0.551, + "boost_control_spec": { + "field_name": "field_name_value", + "attribute_type": 1, + "interpolation_type": 1, + "control_points": [ + { + "attribute_value": "attribute_value_value", + "boost_amount": 0.1306, + } + ], + }, + } + ] + } + ], + } + ], + "modality_configs": [ + { + "modality_type": 1, + "rewriter_config": { + "model_settings": { + "model": "model_value", + "temperature": 0.1198, + }, + "prompt": "prompt_value", + "disabled": True, + }, + "summarization_config": { + "model_settings": {}, + "prompt": "prompt_value", + "disabled": True, + }, + "grounding_config": { + "grounding_level": 0.16040000000000001, + "disabled": True, + }, + } + ], + "filter_parameter_behavior": 2, + }, + "python_function": { + "name": "name_value", + "python_code": "python_code_value", + "description": "description_value", + }, + "mcp_tool": { + "name": "name_value", + "description": "description_value", + "input_schema": {}, + "output_schema": {}, + "server_address": "server_address_value", + "api_authentication": {}, + "tls_config": {}, + "service_directory_config": {}, + }, + "file_search_tool": { + "corpus_type": 1, + "name": "name_value", + "description": "description_value", + "file_corpus": "file_corpus_value", + }, + "system_tool": {"name": "name_value", "description": "description_value"}, + "widget_tool": { + "parameters": {}, + "name": "name_value", + "description": "description_value", + "widget_type": 1, + }, + "name": "name_value", + "display_name": "display_name_value", + "execution_type": 1, + "create_time": {}, + "update_time": {}, + "etag": "etag_value", + "generated_summary": "generated_summary_value", + "tool_fake_config": { + "code_block": {"python_code": "python_code_value"}, + "enable_fake_mode": True, + }, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = agent_service.CreateToolRequest.meta.fields["tool"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["tool"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["tool"][field])): + del request_init["tool"][field][i][subfield] + else: + del request_init["tool"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcc_tool.Tool( + name="name_value", + display_name="display_name_value", + execution_type=common.ExecutionType.SYNCHRONOUS, + etag="etag_value", + generated_summary="generated_summary_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcc_tool.Tool.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_tool(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_tool.Tool) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.execution_type == common.ExecutionType.SYNCHRONOUS + assert response.etag == "etag_value" + assert response.generated_summary == "generated_summary_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_tool_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_create_tool" + ) as post, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_create_tool_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_create_tool" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.CreateToolRequest.pb( + agent_service.CreateToolRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gcc_tool.Tool.to_json(gcc_tool.Tool()) + req.return_value.content = return_value + + request = agent_service.CreateToolRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcc_tool.Tool() + post_with_metadata.return_value = gcc_tool.Tool(), metadata + + client.create_tool( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_tool_rest_bad_request(request_type=agent_service.UpdateToolRequest): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "tool": { + "name": "projects/sample1/locations/sample2/apps/sample3/tools/sample4" + } + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_tool(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.UpdateToolRequest, + dict, + ], +) +def test_update_tool_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "tool": { + "name": "projects/sample1/locations/sample2/apps/sample3/tools/sample4" + } + } + request_init["tool"] = { + "client_function": { + "name": "name_value", + "description": "description_value", + "parameters": { + "type_": 1, + "properties": {}, + "required": ["required_value1", "required_value2"], + "description": "description_value", + "items": {}, + "nullable": True, + "unique_items": True, + "prefix_items": {}, + "additional_properties": {}, + "any_of": {}, + "enum": ["enum_value1", "enum_value2"], + "default": { + "null_value": 0, + "number_value": 0.1285, + "string_value": "string_value_value", + "bool_value": True, + "struct_value": {"fields": {}}, + "list_value": {"values": {}}, + }, + "ref": "ref_value", + "defs": {}, + "title": "title_value", + "min_items": 965, + "max_items": 967, + "minimum": 0.764, + "maximum": 0.766, + }, + "response": {}, + }, + "open_api_tool": { + "open_api_schema": "open_api_schema_value", + "name": "name_value", + "description": "description_value", + "api_authentication": { + "api_key_config": { + "key_name": "key_name_value", + "api_key_secret_version": "api_key_secret_version_value", + "request_location": 1, + }, + "oauth_config": { + "oauth_grant_type": 1, + "client_id": "client_id_value", + "client_secret_version": "client_secret_version_value", + "token_endpoint": "token_endpoint_value", + "scopes": ["scopes_value1", "scopes_value2"], + }, + "service_agent_id_token_auth_config": {}, + "service_account_auth_config": { + "service_account": "service_account_value", + "scopes": ["scopes_value1", "scopes_value2"], + }, + "bearer_token_config": {"token": "token_value"}, + }, + "tls_config": { + "ca_certs": [ + {"display_name": "display_name_value", "cert": b"cert_blob"} + ] + }, + "service_directory_config": {"service": "service_value"}, + "ignore_unknown_fields_": True, + "url": "url_value", + }, + "google_search_tool": { + "name": "name_value", + "description": "description_value", + "context_urls": ["context_urls_value1", "context_urls_value2"], + "preferred_domains": [ + "preferred_domains_value1", + "preferred_domains_value2", + ], + "exclude_domains": ["exclude_domains_value1", "exclude_domains_value2"], + "prompt_config": { + "text_prompt": "text_prompt_value", + "voice_prompt": "voice_prompt_value", + }, + }, + "connector_tool": { + "connection": "connection_value", + "action": { + "connection_action_id": "connection_action_id_value", + "entity_operation": {"entity_id": "entity_id_value", "operation": 1}, + "input_fields": ["input_fields_value1", "input_fields_value2"], + "output_fields": ["output_fields_value1", "output_fields_value2"], + }, + "auth_config": { + "oauth2_auth_code_config": {"oauth_token": "oauth_token_value"}, + "oauth2_jwt_bearer_config": { + "issuer": "issuer_value", + "subject": "subject_value", + "client_key": "client_key_value", + }, + }, + "name": "name_value", + "description": "description_value", + }, + "data_store_tool": { + "data_store_source": { + "filter": "filter_value", + "data_store": { + "name": "name_value", + "type_": 1, + "document_processing_mode": 1, + "display_name": "display_name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "connector_config": { + "collection": "collection_value", + "collection_display_name": "collection_display_name_value", + "data_source": "data_source_value", + }, + }, + }, + "engine_source": { + "engine": "engine_value", + "data_store_sources": {}, + "filter": "filter_value", + }, + "name": "name_value", + "description": "description_value", + "boost_specs": [ + { + "data_stores": ["data_stores_value1", "data_stores_value2"], + "spec": [ + { + "condition_boost_specs": [ + { + "condition": "condition_value", + "boost": 0.551, + "boost_control_spec": { + "field_name": "field_name_value", + "attribute_type": 1, + "interpolation_type": 1, + "control_points": [ + { + "attribute_value": "attribute_value_value", + "boost_amount": 0.1306, + } + ], + }, + } + ] + } + ], + } + ], + "modality_configs": [ + { + "modality_type": 1, + "rewriter_config": { + "model_settings": { + "model": "model_value", + "temperature": 0.1198, + }, + "prompt": "prompt_value", + "disabled": True, + }, + "summarization_config": { + "model_settings": {}, + "prompt": "prompt_value", + "disabled": True, + }, + "grounding_config": { + "grounding_level": 0.16040000000000001, + "disabled": True, + }, + } + ], + "filter_parameter_behavior": 2, + }, + "python_function": { + "name": "name_value", + "python_code": "python_code_value", + "description": "description_value", + }, + "mcp_tool": { + "name": "name_value", + "description": "description_value", + "input_schema": {}, + "output_schema": {}, + "server_address": "server_address_value", + "api_authentication": {}, + "tls_config": {}, + "service_directory_config": {}, + }, + "file_search_tool": { + "corpus_type": 1, + "name": "name_value", + "description": "description_value", + "file_corpus": "file_corpus_value", + }, + "system_tool": {"name": "name_value", "description": "description_value"}, + "widget_tool": { + "parameters": {}, + "name": "name_value", + "description": "description_value", + "widget_type": 1, + }, + "name": "projects/sample1/locations/sample2/apps/sample3/tools/sample4", + "display_name": "display_name_value", + "execution_type": 1, + "create_time": {}, + "update_time": {}, + "etag": "etag_value", + "generated_summary": "generated_summary_value", + "tool_fake_config": { + "code_block": {"python_code": "python_code_value"}, + "enable_fake_mode": True, + }, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = agent_service.UpdateToolRequest.meta.fields["tool"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["tool"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["tool"][field])): + del request_init["tool"][field][i][subfield] + else: + del request_init["tool"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcc_tool.Tool( + name="name_value", + display_name="display_name_value", + execution_type=common.ExecutionType.SYNCHRONOUS, + etag="etag_value", + generated_summary="generated_summary_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcc_tool.Tool.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_tool(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_tool.Tool) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.execution_type == common.ExecutionType.SYNCHRONOUS + assert response.etag == "etag_value" + assert response.generated_summary == "generated_summary_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_tool_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_update_tool" + ) as post, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_update_tool_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_update_tool" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.UpdateToolRequest.pb( + agent_service.UpdateToolRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gcc_tool.Tool.to_json(gcc_tool.Tool()) + req.return_value.content = return_value + + request = agent_service.UpdateToolRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcc_tool.Tool() + post_with_metadata.return_value = gcc_tool.Tool(), metadata + + client.update_tool( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_tool_rest_bad_request(request_type=agent_service.DeleteToolRequest): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/tools/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_tool(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.DeleteToolRequest, + dict, + ], +) +def test_delete_tool_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/tools/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_tool(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_tool_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_delete_tool" + ) as pre: + pre.assert_not_called() + pb_message = agent_service.DeleteToolRequest.pb( + agent_service.DeleteToolRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = agent_service.DeleteToolRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_tool( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_list_guardrails_rest_bad_request( + request_type=agent_service.ListGuardrailsRequest, +): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_guardrails(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.ListGuardrailsRequest, + dict, + ], +) +def test_list_guardrails_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = agent_service.ListGuardrailsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = agent_service.ListGuardrailsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_guardrails(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListGuardrailsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_guardrails_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_list_guardrails" + ) as post, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_list_guardrails_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_list_guardrails" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.ListGuardrailsRequest.pb( + agent_service.ListGuardrailsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = agent_service.ListGuardrailsResponse.to_json( + agent_service.ListGuardrailsResponse() + ) + req.return_value.content = return_value + + request = agent_service.ListGuardrailsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = agent_service.ListGuardrailsResponse() + post_with_metadata.return_value = ( + agent_service.ListGuardrailsResponse(), + metadata, + ) + + client.list_guardrails( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_guardrail_rest_bad_request(request_type=agent_service.GetGuardrailRequest): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/guardrails/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_guardrail(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.GetGuardrailRequest, + dict, + ], +) +def test_get_guardrail_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/guardrails/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = guardrail.Guardrail( + name="name_value", + display_name="display_name_value", + description="description_value", + enabled=True, + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = guardrail.Guardrail.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_guardrail(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, guardrail.Guardrail) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.enabled is True + assert response.etag == "etag_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_guardrail_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_get_guardrail" + ) as post, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_get_guardrail_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_get_guardrail" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.GetGuardrailRequest.pb( + agent_service.GetGuardrailRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = guardrail.Guardrail.to_json(guardrail.Guardrail()) + req.return_value.content = return_value + + request = agent_service.GetGuardrailRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = guardrail.Guardrail() + post_with_metadata.return_value = guardrail.Guardrail(), metadata + + client.get_guardrail( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_guardrail_rest_bad_request( + request_type=agent_service.CreateGuardrailRequest, +): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_guardrail(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.CreateGuardrailRequest, + dict, + ], +) +def test_create_guardrail_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request_init["guardrail"] = { + "content_filter": { + "banned_contents": ["banned_contents_value1", "banned_contents_value2"], + "banned_contents_in_user_input": [ + "banned_contents_in_user_input_value1", + "banned_contents_in_user_input_value2", + ], + "banned_contents_in_agent_response": [ + "banned_contents_in_agent_response_value1", + "banned_contents_in_agent_response_value2", + ], + "match_type": 1, + "disregard_diacritics": True, + }, + "llm_prompt_security": { + "default_settings": { + "default_prompt_template": "default_prompt_template_value" + }, + "custom_policy": { + "max_conversation_messages": 2679, + "model_settings": {"model": "model_value", "temperature": 0.1198}, + "prompt": "prompt_value", + "policy_scope": 1, + "fail_open": True, + "allow_short_utterance": True, + }, + "fail_open": True, + }, + "llm_policy": {}, + "model_safety": {"safety_settings": [{"category": 1, "threshold": 1}]}, + "code_callback": { + "before_agent_callback": { + "python_code": "python_code_value", + "description": "description_value", + "disabled": True, + "proactive_execution_enabled": True, + }, + "after_agent_callback": {}, + "before_model_callback": {}, + "after_model_callback": {}, + }, + "name": "name_value", + "display_name": "display_name_value", + "description": "description_value", + "enabled": True, + "action": { + "respond_immediately": { + "responses": [{"text": "text_value", "disabled": True}] + }, + "transfer_agent": {"agent": "agent_value"}, + "generative_answer": {"prompt": "prompt_value"}, + }, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "etag": "etag_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = agent_service.CreateGuardrailRequest.meta.fields["guardrail"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["guardrail"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["guardrail"][field])): + del request_init["guardrail"][field][i][subfield] + else: + del request_init["guardrail"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcc_guardrail.Guardrail( + name="name_value", + display_name="display_name_value", + description="description_value", + enabled=True, + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcc_guardrail.Guardrail.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_guardrail(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_guardrail.Guardrail) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.enabled is True + assert response.etag == "etag_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_guardrail_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_create_guardrail" + ) as post, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_create_guardrail_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_create_guardrail" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.CreateGuardrailRequest.pb( + agent_service.CreateGuardrailRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gcc_guardrail.Guardrail.to_json(gcc_guardrail.Guardrail()) + req.return_value.content = return_value + + request = agent_service.CreateGuardrailRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcc_guardrail.Guardrail() + post_with_metadata.return_value = gcc_guardrail.Guardrail(), metadata + + client.create_guardrail( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_guardrail_rest_bad_request( + request_type=agent_service.UpdateGuardrailRequest, +): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "guardrail": { + "name": "projects/sample1/locations/sample2/apps/sample3/guardrails/sample4" + } + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_guardrail(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.UpdateGuardrailRequest, + dict, + ], +) +def test_update_guardrail_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "guardrail": { + "name": "projects/sample1/locations/sample2/apps/sample3/guardrails/sample4" + } + } + request_init["guardrail"] = { + "content_filter": { + "banned_contents": ["banned_contents_value1", "banned_contents_value2"], + "banned_contents_in_user_input": [ + "banned_contents_in_user_input_value1", + "banned_contents_in_user_input_value2", + ], + "banned_contents_in_agent_response": [ + "banned_contents_in_agent_response_value1", + "banned_contents_in_agent_response_value2", + ], + "match_type": 1, + "disregard_diacritics": True, + }, + "llm_prompt_security": { + "default_settings": { + "default_prompt_template": "default_prompt_template_value" + }, + "custom_policy": { + "max_conversation_messages": 2679, + "model_settings": {"model": "model_value", "temperature": 0.1198}, + "prompt": "prompt_value", + "policy_scope": 1, + "fail_open": True, + "allow_short_utterance": True, + }, + "fail_open": True, + }, + "llm_policy": {}, + "model_safety": {"safety_settings": [{"category": 1, "threshold": 1}]}, + "code_callback": { + "before_agent_callback": { + "python_code": "python_code_value", + "description": "description_value", + "disabled": True, + "proactive_execution_enabled": True, + }, + "after_agent_callback": {}, + "before_model_callback": {}, + "after_model_callback": {}, + }, + "name": "projects/sample1/locations/sample2/apps/sample3/guardrails/sample4", + "display_name": "display_name_value", + "description": "description_value", + "enabled": True, + "action": { + "respond_immediately": { + "responses": [{"text": "text_value", "disabled": True}] + }, + "transfer_agent": {"agent": "agent_value"}, + "generative_answer": {"prompt": "prompt_value"}, + }, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "etag": "etag_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = agent_service.UpdateGuardrailRequest.meta.fields["guardrail"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["guardrail"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["guardrail"][field])): + del request_init["guardrail"][field][i][subfield] + else: + del request_init["guardrail"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcc_guardrail.Guardrail( + name="name_value", + display_name="display_name_value", + description="description_value", + enabled=True, + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcc_guardrail.Guardrail.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_guardrail(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_guardrail.Guardrail) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.enabled is True + assert response.etag == "etag_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_guardrail_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_update_guardrail" + ) as post, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_update_guardrail_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_update_guardrail" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.UpdateGuardrailRequest.pb( + agent_service.UpdateGuardrailRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gcc_guardrail.Guardrail.to_json(gcc_guardrail.Guardrail()) + req.return_value.content = return_value + + request = agent_service.UpdateGuardrailRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcc_guardrail.Guardrail() + post_with_metadata.return_value = gcc_guardrail.Guardrail(), metadata + + client.update_guardrail( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_guardrail_rest_bad_request( + request_type=agent_service.DeleteGuardrailRequest, +): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/guardrails/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_guardrail(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.DeleteGuardrailRequest, + dict, + ], +) +def test_delete_guardrail_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/guardrails/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_guardrail(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_guardrail_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_delete_guardrail" + ) as pre: + pre.assert_not_called() + pb_message = agent_service.DeleteGuardrailRequest.pb( + agent_service.DeleteGuardrailRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = agent_service.DeleteGuardrailRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_guardrail( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_list_deployments_rest_bad_request( + request_type=agent_service.ListDeploymentsRequest, +): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_deployments(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.ListDeploymentsRequest, + dict, + ], +) +def test_list_deployments_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = agent_service.ListDeploymentsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = agent_service.ListDeploymentsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_deployments(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDeploymentsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_deployments_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_list_deployments" + ) as post, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_list_deployments_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_list_deployments" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.ListDeploymentsRequest.pb( + agent_service.ListDeploymentsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = agent_service.ListDeploymentsResponse.to_json( + agent_service.ListDeploymentsResponse() + ) + req.return_value.content = return_value + + request = agent_service.ListDeploymentsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = agent_service.ListDeploymentsResponse() + post_with_metadata.return_value = ( + agent_service.ListDeploymentsResponse(), + metadata, + ) + + client.list_deployments( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_deployment_rest_bad_request( + request_type=agent_service.GetDeploymentRequest, +): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/deployments/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_deployment(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.GetDeploymentRequest, + dict, + ], +) +def test_get_deployment_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/deployments/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = deployment.Deployment( + name="name_value", + display_name="display_name_value", + app_version="app_version_value", + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = deployment.Deployment.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_deployment(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, deployment.Deployment) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.app_version == "app_version_value" + assert response.etag == "etag_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_deployment_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_get_deployment" + ) as post, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_get_deployment_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_get_deployment" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.GetDeploymentRequest.pb( + agent_service.GetDeploymentRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = deployment.Deployment.to_json(deployment.Deployment()) + req.return_value.content = return_value + + request = agent_service.GetDeploymentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = deployment.Deployment() + post_with_metadata.return_value = deployment.Deployment(), metadata + + client.get_deployment( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_deployment_rest_bad_request( + request_type=agent_service.CreateDeploymentRequest, +): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_deployment(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.CreateDeploymentRequest, + dict, + ], +) +def test_create_deployment_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request_init["deployment"] = { + "name": "name_value", + "display_name": "display_name_value", + "app_version": "app_version_value", + "channel_profile": { + "profile_id": "profile_id_value", + "channel_type": 2, + "persona_property": {"persona": 1}, + "disable_dtmf": True, + "disable_barge_in_control": True, + "web_widget_config": { + "modality": 1, + "theme": 1, + "web_widget_title": "web_widget_title_value", + "security_settings": { + "enable_public_access": True, + "enable_origin_check": True, + "allowed_origins": [ + "allowed_origins_value1", + "allowed_origins_value2", + ], + "enable_recaptcha": True, + }, + }, + "noise_suppression_level": "noise_suppression_level_value", + }, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "etag": "etag_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = agent_service.CreateDeploymentRequest.meta.fields["deployment"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["deployment"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["deployment"][field])): + del request_init["deployment"][field][i][subfield] + else: + del request_init["deployment"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcc_deployment.Deployment( + name="name_value", + display_name="display_name_value", + app_version="app_version_value", + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcc_deployment.Deployment.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_deployment(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_deployment.Deployment) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.app_version == "app_version_value" + assert response.etag == "etag_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_deployment_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_create_deployment" + ) as post, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_create_deployment_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_create_deployment" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.CreateDeploymentRequest.pb( + agent_service.CreateDeploymentRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gcc_deployment.Deployment.to_json(gcc_deployment.Deployment()) + req.return_value.content = return_value + + request = agent_service.CreateDeploymentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcc_deployment.Deployment() + post_with_metadata.return_value = gcc_deployment.Deployment(), metadata + + client.create_deployment( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_deployment_rest_bad_request( + request_type=agent_service.UpdateDeploymentRequest, +): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "deployment": { + "name": "projects/sample1/locations/sample2/apps/sample3/deployments/sample4" + } + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_deployment(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.UpdateDeploymentRequest, + dict, + ], +) +def test_update_deployment_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "deployment": { + "name": "projects/sample1/locations/sample2/apps/sample3/deployments/sample4" + } + } + request_init["deployment"] = { + "name": "projects/sample1/locations/sample2/apps/sample3/deployments/sample4", + "display_name": "display_name_value", + "app_version": "app_version_value", + "channel_profile": { + "profile_id": "profile_id_value", + "channel_type": 2, + "persona_property": {"persona": 1}, + "disable_dtmf": True, + "disable_barge_in_control": True, + "web_widget_config": { + "modality": 1, + "theme": 1, + "web_widget_title": "web_widget_title_value", + "security_settings": { + "enable_public_access": True, + "enable_origin_check": True, + "allowed_origins": [ + "allowed_origins_value1", + "allowed_origins_value2", + ], + "enable_recaptcha": True, + }, + }, + "noise_suppression_level": "noise_suppression_level_value", + }, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "etag": "etag_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = agent_service.UpdateDeploymentRequest.meta.fields["deployment"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["deployment"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["deployment"][field])): + del request_init["deployment"][field][i][subfield] + else: + del request_init["deployment"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcc_deployment.Deployment( + name="name_value", + display_name="display_name_value", + app_version="app_version_value", + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcc_deployment.Deployment.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_deployment(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_deployment.Deployment) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.app_version == "app_version_value" + assert response.etag == "etag_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_deployment_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_update_deployment" + ) as post, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_update_deployment_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_update_deployment" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.UpdateDeploymentRequest.pb( + agent_service.UpdateDeploymentRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gcc_deployment.Deployment.to_json(gcc_deployment.Deployment()) + req.return_value.content = return_value + + request = agent_service.UpdateDeploymentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcc_deployment.Deployment() + post_with_metadata.return_value = gcc_deployment.Deployment(), metadata + + client.update_deployment( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_deployment_rest_bad_request( + request_type=agent_service.DeleteDeploymentRequest, +): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/deployments/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_deployment(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.DeleteDeploymentRequest, + dict, + ], +) +def test_delete_deployment_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/deployments/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_deployment(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_deployment_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_delete_deployment" + ) as pre: + pre.assert_not_called() + pb_message = agent_service.DeleteDeploymentRequest.pb( + agent_service.DeleteDeploymentRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = agent_service.DeleteDeploymentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_deployment( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_list_toolsets_rest_bad_request(request_type=agent_service.ListToolsetsRequest): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_toolsets(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.ListToolsetsRequest, + dict, + ], +) +def test_list_toolsets_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = agent_service.ListToolsetsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = agent_service.ListToolsetsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_toolsets(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListToolsetsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_toolsets_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_list_toolsets" + ) as post, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_list_toolsets_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_list_toolsets" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.ListToolsetsRequest.pb( + agent_service.ListToolsetsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = agent_service.ListToolsetsResponse.to_json( + agent_service.ListToolsetsResponse() + ) + req.return_value.content = return_value + + request = agent_service.ListToolsetsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = agent_service.ListToolsetsResponse() + post_with_metadata.return_value = agent_service.ListToolsetsResponse(), metadata + + client.list_toolsets( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_toolset_rest_bad_request(request_type=agent_service.GetToolsetRequest): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/toolsets/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_toolset(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.GetToolsetRequest, + dict, + ], +) +def test_get_toolset_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/toolsets/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = toolset.Toolset( + name="name_value", + display_name="display_name_value", + description="description_value", + etag="etag_value", + execution_type=common.ExecutionType.SYNCHRONOUS, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = toolset.Toolset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_toolset(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, toolset.Toolset) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.etag == "etag_value" + assert response.execution_type == common.ExecutionType.SYNCHRONOUS + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_toolset_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_get_toolset" + ) as post, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_get_toolset_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_get_toolset" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.GetToolsetRequest.pb( + agent_service.GetToolsetRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = toolset.Toolset.to_json(toolset.Toolset()) + req.return_value.content = return_value + + request = agent_service.GetToolsetRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = toolset.Toolset() + post_with_metadata.return_value = toolset.Toolset(), metadata + + client.get_toolset( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_toolset_rest_bad_request( + request_type=agent_service.CreateToolsetRequest, +): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_toolset(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.CreateToolsetRequest, + dict, + ], +) +def test_create_toolset_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request_init["toolset"] = { + "mcp_toolset": { + "server_address": "server_address_value", + "api_authentication": { + "api_key_config": { + "key_name": "key_name_value", + "api_key_secret_version": "api_key_secret_version_value", + "request_location": 1, + }, + "oauth_config": { + "oauth_grant_type": 1, + "client_id": "client_id_value", + "client_secret_version": "client_secret_version_value", + "token_endpoint": "token_endpoint_value", + "scopes": ["scopes_value1", "scopes_value2"], + }, + "service_agent_id_token_auth_config": {}, + "service_account_auth_config": { + "service_account": "service_account_value", + "scopes": ["scopes_value1", "scopes_value2"], + }, + "bearer_token_config": {"token": "token_value"}, + }, + "service_directory_config": {"service": "service_value"}, + "tls_config": { + "ca_certs": [ + {"display_name": "display_name_value", "cert": b"cert_blob"} + ] + }, + }, + "open_api_toolset": { + "open_api_schema": "open_api_schema_value", + "api_authentication": {}, + "tls_config": {}, + "service_directory_config": {}, + "ignore_unknown_fields_": True, + "url": "url_value", + }, + "connector_toolset": { + "connection": "connection_value", + "auth_config": { + "oauth2_auth_code_config": {"oauth_token": "oauth_token_value"}, + "oauth2_jwt_bearer_config": { + "issuer": "issuer_value", + "subject": "subject_value", + "client_key": "client_key_value", + }, + }, + "connector_actions": [ + { + "connection_action_id": "connection_action_id_value", + "entity_operation": { + "entity_id": "entity_id_value", + "operation": 1, + }, + "input_fields": ["input_fields_value1", "input_fields_value2"], + "output_fields": ["output_fields_value1", "output_fields_value2"], + } + ], + }, + "name": "name_value", + "display_name": "display_name_value", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "etag": "etag_value", + "execution_type": 1, + "tool_fake_config": { + "code_block": {"python_code": "python_code_value"}, + "enable_fake_mode": True, + }, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = agent_service.CreateToolsetRequest.meta.fields["toolset"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["toolset"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["toolset"][field])): + del request_init["toolset"][field][i][subfield] + else: + del request_init["toolset"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcc_toolset.Toolset( + name="name_value", + display_name="display_name_value", + description="description_value", + etag="etag_value", + execution_type=common.ExecutionType.SYNCHRONOUS, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcc_toolset.Toolset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_toolset(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_toolset.Toolset) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.etag == "etag_value" + assert response.execution_type == common.ExecutionType.SYNCHRONOUS + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_toolset_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_create_toolset" + ) as post, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_create_toolset_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_create_toolset" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.CreateToolsetRequest.pb( + agent_service.CreateToolsetRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gcc_toolset.Toolset.to_json(gcc_toolset.Toolset()) + req.return_value.content = return_value + + request = agent_service.CreateToolsetRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcc_toolset.Toolset() + post_with_metadata.return_value = gcc_toolset.Toolset(), metadata + + client.create_toolset( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_toolset_rest_bad_request( + request_type=agent_service.UpdateToolsetRequest, +): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "toolset": { + "name": "projects/sample1/locations/sample2/apps/sample3/toolsets/sample4" + } + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_toolset(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.UpdateToolsetRequest, + dict, + ], +) +def test_update_toolset_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "toolset": { + "name": "projects/sample1/locations/sample2/apps/sample3/toolsets/sample4" + } + } + request_init["toolset"] = { + "mcp_toolset": { + "server_address": "server_address_value", + "api_authentication": { + "api_key_config": { + "key_name": "key_name_value", + "api_key_secret_version": "api_key_secret_version_value", + "request_location": 1, + }, + "oauth_config": { + "oauth_grant_type": 1, + "client_id": "client_id_value", + "client_secret_version": "client_secret_version_value", + "token_endpoint": "token_endpoint_value", + "scopes": ["scopes_value1", "scopes_value2"], + }, + "service_agent_id_token_auth_config": {}, + "service_account_auth_config": { + "service_account": "service_account_value", + "scopes": ["scopes_value1", "scopes_value2"], + }, + "bearer_token_config": {"token": "token_value"}, + }, + "service_directory_config": {"service": "service_value"}, + "tls_config": { + "ca_certs": [ + {"display_name": "display_name_value", "cert": b"cert_blob"} + ] + }, + }, + "open_api_toolset": { + "open_api_schema": "open_api_schema_value", + "api_authentication": {}, + "tls_config": {}, + "service_directory_config": {}, + "ignore_unknown_fields_": True, + "url": "url_value", + }, + "connector_toolset": { + "connection": "connection_value", + "auth_config": { + "oauth2_auth_code_config": {"oauth_token": "oauth_token_value"}, + "oauth2_jwt_bearer_config": { + "issuer": "issuer_value", + "subject": "subject_value", + "client_key": "client_key_value", + }, + }, + "connector_actions": [ + { + "connection_action_id": "connection_action_id_value", + "entity_operation": { + "entity_id": "entity_id_value", + "operation": 1, + }, + "input_fields": ["input_fields_value1", "input_fields_value2"], + "output_fields": ["output_fields_value1", "output_fields_value2"], + } + ], + }, + "name": "projects/sample1/locations/sample2/apps/sample3/toolsets/sample4", + "display_name": "display_name_value", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "etag": "etag_value", + "execution_type": 1, + "tool_fake_config": { + "code_block": {"python_code": "python_code_value"}, + "enable_fake_mode": True, + }, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = agent_service.UpdateToolsetRequest.meta.fields["toolset"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["toolset"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["toolset"][field])): + del request_init["toolset"][field][i][subfield] + else: + del request_init["toolset"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcc_toolset.Toolset( + name="name_value", + display_name="display_name_value", + description="description_value", + etag="etag_value", + execution_type=common.ExecutionType.SYNCHRONOUS, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcc_toolset.Toolset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_toolset(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_toolset.Toolset) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.etag == "etag_value" + assert response.execution_type == common.ExecutionType.SYNCHRONOUS + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_toolset_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_update_toolset" + ) as post, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_update_toolset_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_update_toolset" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.UpdateToolsetRequest.pb( + agent_service.UpdateToolsetRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gcc_toolset.Toolset.to_json(gcc_toolset.Toolset()) + req.return_value.content = return_value + + request = agent_service.UpdateToolsetRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcc_toolset.Toolset() + post_with_metadata.return_value = gcc_toolset.Toolset(), metadata + + client.update_toolset( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_toolset_rest_bad_request( + request_type=agent_service.DeleteToolsetRequest, +): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/toolsets/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_toolset(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.DeleteToolsetRequest, + dict, + ], +) +def test_delete_toolset_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/toolsets/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_toolset(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_toolset_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_delete_toolset" + ) as pre: + pre.assert_not_called() + pb_message = agent_service.DeleteToolsetRequest.pb( + agent_service.DeleteToolsetRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = agent_service.DeleteToolsetRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_toolset( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_list_app_versions_rest_bad_request( + request_type=agent_service.ListAppVersionsRequest, +): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_app_versions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.ListAppVersionsRequest, + dict, + ], +) +def test_list_app_versions_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = agent_service.ListAppVersionsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = agent_service.ListAppVersionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_app_versions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAppVersionsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_app_versions_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_list_app_versions" + ) as post, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_list_app_versions_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_list_app_versions" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.ListAppVersionsRequest.pb( + agent_service.ListAppVersionsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = agent_service.ListAppVersionsResponse.to_json( + agent_service.ListAppVersionsResponse() + ) + req.return_value.content = return_value + + request = agent_service.ListAppVersionsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = agent_service.ListAppVersionsResponse() + post_with_metadata.return_value = ( + agent_service.ListAppVersionsResponse(), + metadata, + ) + + client.list_app_versions( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_app_version_rest_bad_request( + request_type=agent_service.GetAppVersionRequest, +): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/versions/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_app_version(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.GetAppVersionRequest, + dict, + ], +) +def test_get_app_version_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/versions/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = app_version.AppVersion( + name="name_value", + display_name="display_name_value", + description="description_value", + creator="creator_value", + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = app_version.AppVersion.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_app_version(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, app_version.AppVersion) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.creator == "creator_value" + assert response.etag == "etag_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_app_version_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_get_app_version" + ) as post, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_get_app_version_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_get_app_version" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.GetAppVersionRequest.pb( + agent_service.GetAppVersionRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = app_version.AppVersion.to_json(app_version.AppVersion()) + req.return_value.content = return_value + + request = agent_service.GetAppVersionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = app_version.AppVersion() + post_with_metadata.return_value = app_version.AppVersion(), metadata + + client.get_app_version( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_app_version_rest_bad_request( + request_type=agent_service.CreateAppVersionRequest, +): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_app_version(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.CreateAppVersionRequest, + dict, + ], +) +def test_create_app_version_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request_init["app_version"] = { + "name": "name_value", + "display_name": "display_name_value", + "description": "description_value", + "creator": "creator_value", + "create_time": {"seconds": 751, "nanos": 543}, + "snapshot": { + "app": { + "name": "name_value", + "display_name": "display_name_value", + "description": "description_value", + "pinned": True, + "root_agent": "root_agent_value", + "language_settings": { + "default_language_code": "default_language_code_value", + "supported_language_codes": [ + "supported_language_codes_value1", + "supported_language_codes_value2", + ], + "enable_multilingual_support": True, + "fallback_action": "fallback_action_value", + }, + "time_zone_settings": {"time_zone": "time_zone_value"}, + "audio_processing_config": { + "synthesize_speech_configs": {}, + "barge_in_config": { + "disable_barge_in": True, + "barge_in_awareness": True, + }, + "inactivity_timeout": {"seconds": 751, "nanos": 543}, + "ambient_sound_config": { + "prebuilt_ambient_noise": 1, + "gcs_uri": "gcs_uri_value", + "prebuilt_ambient_sound": "prebuilt_ambient_sound_value", + "volume_gain_db": 0.1467, + }, + }, + "logging_settings": { + "redaction_config": { + "enable_redaction": True, + "inspect_template": "inspect_template_value", + "deidentify_template": "deidentify_template_value", + }, + "audio_recording_config": { + "gcs_bucket": "gcs_bucket_value", + "gcs_path_prefix": "gcs_path_prefix_value", + }, + "bigquery_export_settings": { + "enabled": True, + "project": "project_value", + "dataset": "dataset_value", + }, + "cloud_logging_settings": {"enable_cloud_logging": True}, + "conversation_logging_settings": { + "disable_conversation_logging": True + }, + "evaluation_audio_recording_config": {}, + "metric_analysis_settings": {"llm_metrics_opted_out": True}, + }, + "error_handling_settings": {"error_handling_strategy": 1}, + "model_settings": {"model": "model_value", "temperature": 0.1198}, + "tool_execution_mode": 1, + "evaluation_metrics_thresholds": { + "golden_evaluation_metrics_thresholds": { + "turn_level_metrics_thresholds": { + "semantic_similarity_success_threshold": 3966, + "overall_tool_invocation_correctness_threshold": 0.4833, + "semantic_similarity_channel": 1, + }, + "expectation_level_metrics_thresholds": { + "tool_invocation_parameter_correctness_threshold": 0.5037 + }, + "tool_matching_settings": {"extra_tool_call_behavior": 1}, + }, + "hallucination_metric_behavior": 1, + "golden_hallucination_metric_behavior": 1, + "scenario_hallucination_metric_behavior": 1, + }, + "variable_declarations": [ + { + "name": "name_value", + "description": "description_value", + "schema": { + "type_": 1, + "properties": {}, + "required": ["required_value1", "required_value2"], + "description": "description_value", + "items": {}, + "nullable": True, + "unique_items": True, + "prefix_items": {}, + "additional_properties": {}, + "any_of": {}, + "enum": ["enum_value1", "enum_value2"], + "default": { + "null_value": 0, + "number_value": 0.1285, + "string_value": "string_value_value", + "bool_value": True, + "struct_value": {"fields": {}}, + "list_value": {"values": {}}, + }, + "ref": "ref_value", + "defs": {}, + "title": "title_value", + "min_items": 965, + "max_items": 967, + "minimum": 0.764, + "maximum": 0.766, + }, + } + ], + "predefined_variable_declarations": {}, + "global_instruction": "global_instruction_value", + "guardrails": ["guardrails_value1", "guardrails_value2"], + "data_store_settings": { + "engines": [{"name": "name_value", "type_": 1}] + }, + "default_channel_profile": { + "profile_id": "profile_id_value", + "channel_type": 2, + "persona_property": {"persona": 1}, + "disable_dtmf": True, + "disable_barge_in_control": True, + "web_widget_config": { + "modality": 1, + "theme": 1, + "web_widget_title": "web_widget_title_value", + "security_settings": { + "enable_public_access": True, + "enable_origin_check": True, + "allowed_origins": [ + "allowed_origins_value1", + "allowed_origins_value2", + ], + "enable_recaptcha": True, + }, + }, + "noise_suppression_level": "noise_suppression_level_value", + }, + "metadata": {}, + "create_time": {}, + "update_time": {}, + "etag": "etag_value", + "deployment_count": 1737, + "client_certificate_settings": { + "tls_certificate": "tls_certificate_value", + "private_key": "private_key_value", + "passphrase": "passphrase_value", + }, + "locked": True, + "evaluation_personas": [ + { + "name": "name_value", + "description": "description_value", + "display_name": "display_name_value", + "personality": "personality_value", + "speech_config": { + "speaking_rate": 0.1373, + "environment": 3, + "voice_id": "voice_id_value", + }, + } + ], + "evaluation_settings": { + "scenario_conversation_initiator": 1, + "golden_run_method": 1, + "golden_evaluation_tool_call_behaviour": 1, + "scenario_evaluation_tool_call_behaviour": 1, + }, + }, + "agents": [ + { + "llm_agent": {}, + "remote_dialogflow_agent": { + "agent": "agent_value", + "flow_id": "flow_id_value", + "environment_id": "environment_id_value", + "input_variable_mapping": {}, + "output_variable_mapping": {}, + "respect_response_interruption_settings": True, + }, + "name": "name_value", + "display_name": "display_name_value", + "description": "description_value", + "model_settings": {}, + "instruction": "instruction_value", + "tools": ["tools_value1", "tools_value2"], + "child_agents": ["child_agents_value1", "child_agents_value2"], + "before_agent_callbacks": [ + { + "python_code": "python_code_value", + "description": "description_value", + "disabled": True, + "proactive_execution_enabled": True, + } + ], + "after_agent_callbacks": {}, + "before_model_callbacks": {}, + "after_model_callbacks": {}, + "before_tool_callbacks": {}, + "after_tool_callbacks": {}, + "create_time": {}, + "update_time": {}, + "guardrails": ["guardrails_value1", "guardrails_value2"], + "etag": "etag_value", + "toolsets": [ + { + "toolset": "toolset_value", + "tool_ids": ["tool_ids_value1", "tool_ids_value2"], + } + ], + "generated_summary": "generated_summary_value", + "transfer_rules": [ + { + "deterministic_transfer": { + "expression_condition": { + "expression": "expression_value" + }, + "python_code_condition": { + "python_code": "python_code_value" + }, + }, + "disable_planner_transfer": {"expression_condition": {}}, + "child_agent": "child_agent_value", + "direction": 1, + } + ], + } + ], + "tools": [ + { + "client_function": { + "name": "name_value", + "description": "description_value", + "parameters": {}, + "response": {}, + }, + "open_api_tool": { + "open_api_schema": "open_api_schema_value", + "name": "name_value", + "description": "description_value", + "api_authentication": { + "api_key_config": { + "key_name": "key_name_value", + "api_key_secret_version": "api_key_secret_version_value", + "request_location": 1, + }, + "oauth_config": { + "oauth_grant_type": 1, + "client_id": "client_id_value", + "client_secret_version": "client_secret_version_value", + "token_endpoint": "token_endpoint_value", + "scopes": ["scopes_value1", "scopes_value2"], + }, + "service_agent_id_token_auth_config": {}, + "service_account_auth_config": { + "service_account": "service_account_value", + "scopes": ["scopes_value1", "scopes_value2"], + }, + "bearer_token_config": {"token": "token_value"}, + }, + "tls_config": { + "ca_certs": [ + { + "display_name": "display_name_value", + "cert": b"cert_blob", + } + ] + }, + "service_directory_config": {"service": "service_value"}, + "ignore_unknown_fields_": True, + "url": "url_value", + }, + "google_search_tool": { + "name": "name_value", + "description": "description_value", + "context_urls": ["context_urls_value1", "context_urls_value2"], + "preferred_domains": [ + "preferred_domains_value1", + "preferred_domains_value2", + ], + "exclude_domains": [ + "exclude_domains_value1", + "exclude_domains_value2", + ], + "prompt_config": { + "text_prompt": "text_prompt_value", + "voice_prompt": "voice_prompt_value", + }, + }, + "connector_tool": { + "connection": "connection_value", + "action": { + "connection_action_id": "connection_action_id_value", + "entity_operation": { + "entity_id": "entity_id_value", + "operation": 1, + }, + "input_fields": [ + "input_fields_value1", + "input_fields_value2", + ], + "output_fields": [ + "output_fields_value1", + "output_fields_value2", + ], + }, + "auth_config": { + "oauth2_auth_code_config": { + "oauth_token": "oauth_token_value" + }, + "oauth2_jwt_bearer_config": { + "issuer": "issuer_value", + "subject": "subject_value", + "client_key": "client_key_value", + }, + }, + "name": "name_value", + "description": "description_value", + }, + "data_store_tool": { + "data_store_source": { + "filter": "filter_value", + "data_store": { + "name": "name_value", + "type_": 1, + "document_processing_mode": 1, + "display_name": "display_name_value", + "create_time": {}, + "connector_config": { + "collection": "collection_value", + "collection_display_name": "collection_display_name_value", + "data_source": "data_source_value", + }, + }, + }, + "engine_source": { + "engine": "engine_value", + "data_store_sources": {}, + "filter": "filter_value", + }, + "name": "name_value", + "description": "description_value", + "boost_specs": [ + { + "data_stores": [ + "data_stores_value1", + "data_stores_value2", + ], + "spec": [ + { + "condition_boost_specs": [ + { + "condition": "condition_value", + "boost": 0.551, + "boost_control_spec": { + "field_name": "field_name_value", + "attribute_type": 1, + "interpolation_type": 1, + "control_points": [ + { + "attribute_value": "attribute_value_value", + "boost_amount": 0.1306, + } + ], + }, + } + ] + } + ], + } + ], + "modality_configs": [ + { + "modality_type": 1, + "rewriter_config": { + "model_settings": {}, + "prompt": "prompt_value", + "disabled": True, + }, + "summarization_config": { + "model_settings": {}, + "prompt": "prompt_value", + "disabled": True, + }, + "grounding_config": { + "grounding_level": 0.16040000000000001, + "disabled": True, + }, + } + ], + "filter_parameter_behavior": 2, + }, + "python_function": { + "name": "name_value", + "python_code": "python_code_value", + "description": "description_value", + }, + "mcp_tool": { + "name": "name_value", + "description": "description_value", + "input_schema": {}, + "output_schema": {}, + "server_address": "server_address_value", + "api_authentication": {}, + "tls_config": {}, + "service_directory_config": {}, + }, + "file_search_tool": { + "corpus_type": 1, + "name": "name_value", + "description": "description_value", + "file_corpus": "file_corpus_value", + }, + "system_tool": { + "name": "name_value", + "description": "description_value", + }, + "widget_tool": { + "parameters": {}, + "name": "name_value", + "description": "description_value", + "widget_type": 1, + }, + "name": "name_value", + "display_name": "display_name_value", + "execution_type": 1, + "create_time": {}, + "update_time": {}, + "etag": "etag_value", + "generated_summary": "generated_summary_value", + "tool_fake_config": { + "code_block": {"python_code": "python_code_value"}, + "enable_fake_mode": True, + }, + } + ], + "examples": [ + { + "name": "name_value", + "display_name": "display_name_value", + "description": "description_value", + "entry_agent": "entry_agent_value", + "messages": [ + { + "role": "role_value", + "chunks": [ + { + "text": "text_value", + "transcript": "transcript_value", + "blob": { + "mime_type": "mime_type_value", + "data": b"data_blob", + }, + "payload": {}, + "image": { + "mime_type": "mime_type_value", + "data": b"data_blob", + }, + "tool_call": { + "tool": "tool_value", + "toolset_tool": { + "toolset": "toolset_value", + "tool_id": "tool_id_value", + }, + "id": "id_value", + "display_name": "display_name_value", + "args": {}, + }, + "tool_response": { + "tool": "tool_value", + "toolset_tool": {}, + "id": "id_value", + "display_name": "display_name_value", + "response": {}, + }, + "agent_transfer": { + "target_agent": "target_agent_value", + "display_name": "display_name_value", + }, + "updated_variables": {}, + "default_variables": {}, + } + ], + "event_time": {}, + } + ], + "create_time": {}, + "update_time": {}, + "invalid": True, + "etag": "etag_value", + } + ], + "guardrails": [ + { + "content_filter": { + "banned_contents": [ + "banned_contents_value1", + "banned_contents_value2", + ], + "banned_contents_in_user_input": [ + "banned_contents_in_user_input_value1", + "banned_contents_in_user_input_value2", + ], + "banned_contents_in_agent_response": [ + "banned_contents_in_agent_response_value1", + "banned_contents_in_agent_response_value2", + ], + "match_type": 1, + "disregard_diacritics": True, + }, + "llm_prompt_security": { + "default_settings": { + "default_prompt_template": "default_prompt_template_value" + }, + "custom_policy": { + "max_conversation_messages": 2679, + "model_settings": {}, + "prompt": "prompt_value", + "policy_scope": 1, + "fail_open": True, + "allow_short_utterance": True, + }, + "fail_open": True, + }, + "llm_policy": {}, + "model_safety": { + "safety_settings": [{"category": 1, "threshold": 1}] + }, + "code_callback": { + "before_agent_callback": {}, + "after_agent_callback": {}, + "before_model_callback": {}, + "after_model_callback": {}, + }, + "name": "name_value", + "display_name": "display_name_value", + "description": "description_value", + "enabled": True, + "action": { + "respond_immediately": { + "responses": [{"text": "text_value", "disabled": True}] + }, + "transfer_agent": {"agent": "agent_value"}, + "generative_answer": {"prompt": "prompt_value"}, + }, + "create_time": {}, + "update_time": {}, + "etag": "etag_value", + } + ], + "toolsets": [ + { + "mcp_toolset": { + "server_address": "server_address_value", + "api_authentication": {}, + "service_directory_config": {}, + "tls_config": {}, + }, + "open_api_toolset": { + "open_api_schema": "open_api_schema_value", + "api_authentication": {}, + "tls_config": {}, + "service_directory_config": {}, + "ignore_unknown_fields_": True, + "url": "url_value", + }, + "connector_toolset": { + "connection": "connection_value", + "auth_config": {}, + "connector_actions": {}, + }, + "name": "name_value", + "display_name": "display_name_value", + "description": "description_value", + "create_time": {}, + "update_time": {}, + "etag": "etag_value", + "execution_type": 1, + "tool_fake_config": {}, + } + ], + }, + "etag": "etag_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = agent_service.CreateAppVersionRequest.meta.fields["app_version"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["app_version"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["app_version"][field])): + del request_init["app_version"][field][i][subfield] + else: + del request_init["app_version"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcc_app_version.AppVersion( + name="name_value", + display_name="display_name_value", + description="description_value", + creator="creator_value", + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcc_app_version.AppVersion.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_app_version(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_app_version.AppVersion) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.creator == "creator_value" + assert response.etag == "etag_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_app_version_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_create_app_version" + ) as post, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_create_app_version_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_create_app_version" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.CreateAppVersionRequest.pb( + agent_service.CreateAppVersionRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gcc_app_version.AppVersion.to_json(gcc_app_version.AppVersion()) + req.return_value.content = return_value + + request = agent_service.CreateAppVersionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcc_app_version.AppVersion() + post_with_metadata.return_value = gcc_app_version.AppVersion(), metadata + + client.create_app_version( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_app_version_rest_bad_request( + request_type=agent_service.DeleteAppVersionRequest, +): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/versions/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_app_version(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.DeleteAppVersionRequest, + dict, + ], +) +def test_delete_app_version_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/versions/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_app_version(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_app_version_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_delete_app_version" + ) as pre: + pre.assert_not_called() + pb_message = agent_service.DeleteAppVersionRequest.pb( + agent_service.DeleteAppVersionRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = agent_service.DeleteAppVersionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_app_version( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_restore_app_version_rest_bad_request( + request_type=agent_service.RestoreAppVersionRequest, +): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/versions/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.restore_app_version(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.RestoreAppVersionRequest, + dict, + ], +) +def test_restore_app_version_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/versions/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.restore_app_version(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_restore_app_version_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.AgentServiceRestInterceptor, "post_restore_app_version" + ) as post, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_restore_app_version_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_restore_app_version" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.RestoreAppVersionRequest.pb( + agent_service.RestoreAppVersionRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = agent_service.RestoreAppVersionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.restore_app_version( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_changelogs_rest_bad_request( + request_type=agent_service.ListChangelogsRequest, +): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_changelogs(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.ListChangelogsRequest, + dict, + ], +) +def test_list_changelogs_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = agent_service.ListChangelogsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = agent_service.ListChangelogsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_changelogs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListChangelogsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_changelogs_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_list_changelogs" + ) as post, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_list_changelogs_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_list_changelogs" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.ListChangelogsRequest.pb( + agent_service.ListChangelogsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = agent_service.ListChangelogsResponse.to_json( + agent_service.ListChangelogsResponse() + ) + req.return_value.content = return_value + + request = agent_service.ListChangelogsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = agent_service.ListChangelogsResponse() + post_with_metadata.return_value = ( + agent_service.ListChangelogsResponse(), + metadata, + ) + + client.list_changelogs( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_changelog_rest_bad_request(request_type=agent_service.GetChangelogRequest): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/changelogs/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_changelog(request) + + +@pytest.mark.parametrize( + "request_type", + [ + agent_service.GetChangelogRequest, + dict, + ], +) +def test_get_changelog_rest_call_success(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/changelogs/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = changelog.Changelog( + name="name_value", + author="author_value", + display_name="display_name_value", + description="description_value", + resource="resource_value", + resource_type="resource_type_value", + action="action_value", + sequence_number=1601, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = changelog.Changelog.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_changelog(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, changelog.Changelog) + assert response.name == "name_value" + assert response.author == "author_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.resource == "resource_value" + assert response.resource_type == "resource_type_value" + assert response.action == "action_value" + assert response.sequence_number == 1601 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_changelog_rest_interceptors(null_interceptor): + transport = transports.AgentServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AgentServiceRestInterceptor(), + ) + client = AgentServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_get_changelog" + ) as post, mock.patch.object( + transports.AgentServiceRestInterceptor, "post_get_changelog_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.AgentServiceRestInterceptor, "pre_get_changelog" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = agent_service.GetChangelogRequest.pb( + agent_service.GetChangelogRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = changelog.Changelog.to_json(changelog.Changelog()) + req.return_value.content = return_value + + request = agent_service.GetChangelogRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = changelog.Changelog() + post_with_metadata.return_value = changelog.Changelog(), metadata + + client.get_changelog( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_location(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.GetLocationRequest, + dict, + ], +) +def test_get_location_rest(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_list_locations_rest_bad_request( + request_type=locations_pb2.ListLocationsRequest, +): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"name": "projects/sample1"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_locations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.ListLocationsRequest, + dict, + ], +) +def test_list_locations_rest(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_cancel_operation_rest_bad_request( + request_type=operations_pb2.CancelOperationRequest, +): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_rest_bad_request( + request_type=operations_pb2.DeleteOperationRequest, +): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_apps_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_apps), "__call__") as call: + client.list_apps(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.ListAppsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_app_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_app), "__call__") as call: + client.get_app(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.GetAppRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_app_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_app), "__call__") as call: + client.create_app(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.CreateAppRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_app_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_app), "__call__") as call: + client.update_app(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.UpdateAppRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_app_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_app), "__call__") as call: + client.delete_app(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.DeleteAppRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_export_app_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.export_app), "__call__") as call: + client.export_app(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.ExportAppRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_app_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.import_app), "__call__") as call: + client.import_app(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.ImportAppRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_agents_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_agents), "__call__") as call: + client.list_agents(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.ListAgentsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_agent_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_agent), "__call__") as call: + client.get_agent(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.GetAgentRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_agent_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_agent), "__call__") as call: + client.create_agent(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.CreateAgentRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_agent_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_agent), "__call__") as call: + client.update_agent(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.UpdateAgentRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_agent_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_agent), "__call__") as call: + client.delete_agent(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.DeleteAgentRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_examples_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_examples), "__call__") as call: + client.list_examples(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.ListExamplesRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_example_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_example), "__call__") as call: + client.get_example(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.GetExampleRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_example_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_example), "__call__") as call: + client.create_example(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.CreateExampleRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_example_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_example), "__call__") as call: + client.update_example(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.UpdateExampleRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_example_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_example), "__call__") as call: + client.delete_example(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.DeleteExampleRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_tools_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_tools), "__call__") as call: + client.list_tools(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.ListToolsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_tool_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_tool), "__call__") as call: + client.get_tool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.GetToolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_conversations_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_conversations), "__call__" + ) as call: + client.list_conversations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.ListConversationsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_conversation_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_conversation), "__call__") as call: + client.get_conversation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.GetConversationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_conversation_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_conversation), "__call__" + ) as call: + client.delete_conversation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.DeleteConversationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_batch_delete_conversations_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.batch_delete_conversations), "__call__" + ) as call: + client.batch_delete_conversations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.BatchDeleteConversationsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_tool_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_tool), "__call__") as call: + client.create_tool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.CreateToolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_tool_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_tool), "__call__") as call: + client.update_tool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.UpdateToolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_tool_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_tool), "__call__") as call: + client.delete_tool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.DeleteToolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_guardrails_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_guardrails), "__call__") as call: + client.list_guardrails(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.ListGuardrailsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_guardrail_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_guardrail), "__call__") as call: + client.get_guardrail(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.GetGuardrailRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_guardrail_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_guardrail), "__call__") as call: + client.create_guardrail(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.CreateGuardrailRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_guardrail_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_guardrail), "__call__") as call: + client.update_guardrail(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.UpdateGuardrailRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_guardrail_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_guardrail), "__call__") as call: + client.delete_guardrail(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.DeleteGuardrailRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_deployments_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_deployments), "__call__") as call: + client.list_deployments(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.ListDeploymentsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_deployment_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_deployment), "__call__") as call: + client.get_deployment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.GetDeploymentRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_deployment_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_deployment), "__call__" + ) as call: + client.create_deployment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.CreateDeploymentRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_deployment_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_deployment), "__call__" + ) as call: + client.update_deployment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.UpdateDeploymentRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_deployment_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_deployment), "__call__" + ) as call: + client.delete_deployment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.DeleteDeploymentRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_toolsets_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_toolsets), "__call__") as call: + client.list_toolsets(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.ListToolsetsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_toolset_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_toolset), "__call__") as call: + client.get_toolset(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.GetToolsetRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_toolset_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_toolset), "__call__") as call: + client.create_toolset(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.CreateToolsetRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_toolset_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_toolset), "__call__") as call: + client.update_toolset(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.UpdateToolsetRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_toolset_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_toolset), "__call__") as call: + client.delete_toolset(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.DeleteToolsetRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_app_versions_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_app_versions), "__call__" + ) as call: + client.list_app_versions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.ListAppVersionsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_app_version_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_app_version), "__call__") as call: + client.get_app_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.GetAppVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_app_version_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_app_version), "__call__" + ) as call: + client.create_app_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.CreateAppVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_app_version_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_app_version), "__call__" + ) as call: + client.delete_app_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.DeleteAppVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_restore_app_version_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.restore_app_version), "__call__" + ) as call: + client.restore_app_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.RestoreAppVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_changelogs_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_changelogs), "__call__") as call: + client.list_changelogs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.ListChangelogsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_changelog_empty_call_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_changelog), "__call__") as call: + client.get_changelog(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = agent_service.GetChangelogRequest() + + assert args[0] == request_msg + + +def test_agent_service_rest_lro_client(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AgentServiceGrpcTransport, + ) + + +def test_agent_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AgentServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_agent_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.ces_v1beta.services.agent_service.transports.AgentServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.AgentServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_apps", + "get_app", + "create_app", + "update_app", + "delete_app", + "export_app", + "import_app", + "list_agents", + "get_agent", + "create_agent", + "update_agent", + "delete_agent", + "list_examples", + "get_example", + "create_example", + "update_example", + "delete_example", + "list_tools", + "get_tool", + "list_conversations", + "get_conversation", + "delete_conversation", + "batch_delete_conversations", + "create_tool", + "update_tool", + "delete_tool", + "list_guardrails", + "get_guardrail", + "create_guardrail", + "update_guardrail", + "delete_guardrail", + "list_deployments", + "get_deployment", + "create_deployment", + "update_deployment", + "delete_deployment", + "list_toolsets", + "get_toolset", + "create_toolset", + "update_toolset", + "delete_toolset", + "list_app_versions", + "get_app_version", + "create_app_version", + "delete_app_version", + "restore_app_version", + "list_changelogs", + "get_changelog", + "get_location", + "list_locations", + "get_operation", + "cancel_operation", + "delete_operation", + "list_operations", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_agent_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.ces_v1beta.services.agent_service.transports.AgentServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AgentServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/ces", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +def test_agent_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.ces_v1beta.services.agent_service.transports.AgentServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AgentServiceTransport() + adc.assert_called_once() + + +def test_agent_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + AgentServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/ces", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AgentServiceGrpcTransport, + transports.AgentServiceGrpcAsyncIOTransport, + ], +) +def test_agent_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/ces", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AgentServiceGrpcTransport, + transports.AgentServiceGrpcAsyncIOTransport, + transports.AgentServiceRestTransport, + ], +) +def test_agent_service_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AgentServiceGrpcTransport, grpc_helpers), + (transports.AgentServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_agent_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "ces.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/ces", + "https://www.googleapis.com/auth/cloud-platform", + ), + scopes=["1", "2"], + default_host="ces.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.AgentServiceGrpcTransport, transports.AgentServiceGrpcAsyncIOTransport], +) +def test_agent_service_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_agent_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.AgentServiceRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_agent_service_host_no_port(transport_name): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint="ces.googleapis.com"), + transport=transport_name, + ) + assert client.transport._host == ( + "ces.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://ces.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_agent_service_host_with_port(transport_name): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="ces.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "ces.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://ces.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_agent_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = AgentServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = AgentServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_apps._session + session2 = client2.transport.list_apps._session + assert session1 != session2 + session1 = client1.transport.get_app._session + session2 = client2.transport.get_app._session + assert session1 != session2 + session1 = client1.transport.create_app._session + session2 = client2.transport.create_app._session + assert session1 != session2 + session1 = client1.transport.update_app._session + session2 = client2.transport.update_app._session + assert session1 != session2 + session1 = client1.transport.delete_app._session + session2 = client2.transport.delete_app._session + assert session1 != session2 + session1 = client1.transport.export_app._session + session2 = client2.transport.export_app._session + assert session1 != session2 + session1 = client1.transport.import_app._session + session2 = client2.transport.import_app._session + assert session1 != session2 + session1 = client1.transport.list_agents._session + session2 = client2.transport.list_agents._session + assert session1 != session2 + session1 = client1.transport.get_agent._session + session2 = client2.transport.get_agent._session + assert session1 != session2 + session1 = client1.transport.create_agent._session + session2 = client2.transport.create_agent._session + assert session1 != session2 + session1 = client1.transport.update_agent._session + session2 = client2.transport.update_agent._session + assert session1 != session2 + session1 = client1.transport.delete_agent._session + session2 = client2.transport.delete_agent._session + assert session1 != session2 + session1 = client1.transport.list_examples._session + session2 = client2.transport.list_examples._session + assert session1 != session2 + session1 = client1.transport.get_example._session + session2 = client2.transport.get_example._session + assert session1 != session2 + session1 = client1.transport.create_example._session + session2 = client2.transport.create_example._session + assert session1 != session2 + session1 = client1.transport.update_example._session + session2 = client2.transport.update_example._session + assert session1 != session2 + session1 = client1.transport.delete_example._session + session2 = client2.transport.delete_example._session + assert session1 != session2 + session1 = client1.transport.list_tools._session + session2 = client2.transport.list_tools._session + assert session1 != session2 + session1 = client1.transport.get_tool._session + session2 = client2.transport.get_tool._session + assert session1 != session2 + session1 = client1.transport.list_conversations._session + session2 = client2.transport.list_conversations._session + assert session1 != session2 + session1 = client1.transport.get_conversation._session + session2 = client2.transport.get_conversation._session + assert session1 != session2 + session1 = client1.transport.delete_conversation._session + session2 = client2.transport.delete_conversation._session + assert session1 != session2 + session1 = client1.transport.batch_delete_conversations._session + session2 = client2.transport.batch_delete_conversations._session + assert session1 != session2 + session1 = client1.transport.create_tool._session + session2 = client2.transport.create_tool._session + assert session1 != session2 + session1 = client1.transport.update_tool._session + session2 = client2.transport.update_tool._session + assert session1 != session2 + session1 = client1.transport.delete_tool._session + session2 = client2.transport.delete_tool._session + assert session1 != session2 + session1 = client1.transport.list_guardrails._session + session2 = client2.transport.list_guardrails._session + assert session1 != session2 + session1 = client1.transport.get_guardrail._session + session2 = client2.transport.get_guardrail._session + assert session1 != session2 + session1 = client1.transport.create_guardrail._session + session2 = client2.transport.create_guardrail._session + assert session1 != session2 + session1 = client1.transport.update_guardrail._session + session2 = client2.transport.update_guardrail._session + assert session1 != session2 + session1 = client1.transport.delete_guardrail._session + session2 = client2.transport.delete_guardrail._session + assert session1 != session2 + session1 = client1.transport.list_deployments._session + session2 = client2.transport.list_deployments._session + assert session1 != session2 + session1 = client1.transport.get_deployment._session + session2 = client2.transport.get_deployment._session + assert session1 != session2 + session1 = client1.transport.create_deployment._session + session2 = client2.transport.create_deployment._session + assert session1 != session2 + session1 = client1.transport.update_deployment._session + session2 = client2.transport.update_deployment._session + assert session1 != session2 + session1 = client1.transport.delete_deployment._session + session2 = client2.transport.delete_deployment._session + assert session1 != session2 + session1 = client1.transport.list_toolsets._session + session2 = client2.transport.list_toolsets._session + assert session1 != session2 + session1 = client1.transport.get_toolset._session + session2 = client2.transport.get_toolset._session + assert session1 != session2 + session1 = client1.transport.create_toolset._session + session2 = client2.transport.create_toolset._session + assert session1 != session2 + session1 = client1.transport.update_toolset._session + session2 = client2.transport.update_toolset._session + assert session1 != session2 + session1 = client1.transport.delete_toolset._session + session2 = client2.transport.delete_toolset._session + assert session1 != session2 + session1 = client1.transport.list_app_versions._session + session2 = client2.transport.list_app_versions._session + assert session1 != session2 + session1 = client1.transport.get_app_version._session + session2 = client2.transport.get_app_version._session + assert session1 != session2 + session1 = client1.transport.create_app_version._session + session2 = client2.transport.create_app_version._session + assert session1 != session2 + session1 = client1.transport.delete_app_version._session + session2 = client2.transport.delete_app_version._session + assert session1 != session2 + session1 = client1.transport.restore_app_version._session + session2 = client2.transport.restore_app_version._session + assert session1 != session2 + session1 = client1.transport.list_changelogs._session + session2 = client2.transport.list_changelogs._session + assert session1 != session2 + session1 = client1.transport.get_changelog._session + session2 = client2.transport.get_changelog._session + assert session1 != session2 + + +def test_agent_service_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AgentServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_agent_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AgentServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.filterwarnings("ignore::FutureWarning") +@pytest.mark.parametrize( + "transport_class", + [transports.AgentServiceGrpcTransport, transports.AgentServiceGrpcAsyncIOTransport], +) +def test_agent_service_transport_channel_mtls_with_client_cert_source(transport_class): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [transports.AgentServiceGrpcTransport, transports.AgentServiceGrpcAsyncIOTransport], +) +def test_agent_service_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_agent_service_grpc_lro_client(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_agent_service_grpc_lro_async_client(): + client = AgentServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_agent_path(): + project = "squid" + location = "clam" + app = "whelk" + agent = "octopus" + expected = ( + "projects/{project}/locations/{location}/apps/{app}/agents/{agent}".format( + project=project, + location=location, + app=app, + agent=agent, + ) + ) + actual = AgentServiceClient.agent_path(project, location, app, agent) + assert expected == actual + + +def test_parse_agent_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "app": "cuttlefish", + "agent": "mussel", + } + path = AgentServiceClient.agent_path(**expected) + + # Check that the path construction is reversible. + actual = AgentServiceClient.parse_agent_path(path) + assert expected == actual + + +def test_app_path(): + project = "winkle" + location = "nautilus" + app = "scallop" + expected = "projects/{project}/locations/{location}/apps/{app}".format( + project=project, + location=location, + app=app, + ) + actual = AgentServiceClient.app_path(project, location, app) + assert expected == actual + + +def test_parse_app_path(): + expected = { + "project": "abalone", + "location": "squid", + "app": "clam", + } + path = AgentServiceClient.app_path(**expected) + + # Check that the path construction is reversible. + actual = AgentServiceClient.parse_app_path(path) + assert expected == actual + + +def test_app_version_path(): + project = "whelk" + location = "octopus" + app = "oyster" + version = "nudibranch" + expected = ( + "projects/{project}/locations/{location}/apps/{app}/versions/{version}".format( + project=project, + location=location, + app=app, + version=version, + ) + ) + actual = AgentServiceClient.app_version_path(project, location, app, version) + assert expected == actual + + +def test_parse_app_version_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "app": "winkle", + "version": "nautilus", + } + path = AgentServiceClient.app_version_path(**expected) + + # Check that the path construction is reversible. + actual = AgentServiceClient.parse_app_version_path(path) + assert expected == actual + + +def test_changelog_path(): + project = "scallop" + location = "abalone" + app = "squid" + changelog = "clam" + expected = "projects/{project}/locations/{location}/apps/{app}/changelogs/{changelog}".format( + project=project, + location=location, + app=app, + changelog=changelog, + ) + actual = AgentServiceClient.changelog_path(project, location, app, changelog) + assert expected == actual + + +def test_parse_changelog_path(): + expected = { + "project": "whelk", + "location": "octopus", + "app": "oyster", + "changelog": "nudibranch", + } + path = AgentServiceClient.changelog_path(**expected) + + # Check that the path construction is reversible. + actual = AgentServiceClient.parse_changelog_path(path) + assert expected == actual + + +def test_conversation_path(): + project = "cuttlefish" + location = "mussel" + app = "winkle" + conversation = "nautilus" + expected = "projects/{project}/locations/{location}/apps/{app}/conversations/{conversation}".format( + project=project, + location=location, + app=app, + conversation=conversation, + ) + actual = AgentServiceClient.conversation_path(project, location, app, conversation) + assert expected == actual + + +def test_parse_conversation_path(): + expected = { + "project": "scallop", + "location": "abalone", + "app": "squid", + "conversation": "clam", + } + path = AgentServiceClient.conversation_path(**expected) + + # Check that the path construction is reversible. + actual = AgentServiceClient.parse_conversation_path(path) + assert expected == actual + + +def test_deidentify_template_path(): + organization = "whelk" + location = "octopus" + deidentify_template = "oyster" + expected = "organizations/{organization}/locations/{location}/deidentifyTemplates/{deidentify_template}".format( + organization=organization, + location=location, + deidentify_template=deidentify_template, + ) + actual = AgentServiceClient.deidentify_template_path( + organization, location, deidentify_template + ) + assert expected == actual + + +def test_parse_deidentify_template_path(): + expected = { + "organization": "nudibranch", + "location": "cuttlefish", + "deidentify_template": "mussel", + } + path = AgentServiceClient.deidentify_template_path(**expected) + + # Check that the path construction is reversible. + actual = AgentServiceClient.parse_deidentify_template_path(path) + assert expected == actual + + +def test_deployment_path(): + project = "winkle" + location = "nautilus" + app = "scallop" + deployment = "abalone" + expected = "projects/{project}/locations/{location}/apps/{app}/deployments/{deployment}".format( + project=project, + location=location, + app=app, + deployment=deployment, + ) + actual = AgentServiceClient.deployment_path(project, location, app, deployment) + assert expected == actual + + +def test_parse_deployment_path(): + expected = { + "project": "squid", + "location": "clam", + "app": "whelk", + "deployment": "octopus", + } + path = AgentServiceClient.deployment_path(**expected) + + # Check that the path construction is reversible. + actual = AgentServiceClient.parse_deployment_path(path) + assert expected == actual + + +def test_dialogflow_agent_path(): + project = "oyster" + location = "nudibranch" + agent = "cuttlefish" + expected = "projects/{project}/locations/{location}/agents/{agent}".format( + project=project, + location=location, + agent=agent, + ) + actual = AgentServiceClient.dialogflow_agent_path(project, location, agent) + assert expected == actual + + +def test_parse_dialogflow_agent_path(): + expected = { + "project": "mussel", + "location": "winkle", + "agent": "nautilus", + } + path = AgentServiceClient.dialogflow_agent_path(**expected) + + # Check that the path construction is reversible. + actual = AgentServiceClient.parse_dialogflow_agent_path(path) + assert expected == actual + + +def test_engine_path(): + project = "scallop" + location = "abalone" + collection = "squid" + engine = "clam" + expected = "projects/{project}/locations/{location}/collections/{collection}/engines/{engine}".format( + project=project, + location=location, + collection=collection, + engine=engine, + ) + actual = AgentServiceClient.engine_path(project, location, collection, engine) + assert expected == actual + + +def test_parse_engine_path(): + expected = { + "project": "whelk", + "location": "octopus", + "collection": "oyster", + "engine": "nudibranch", + } + path = AgentServiceClient.engine_path(**expected) + + # Check that the path construction is reversible. + actual = AgentServiceClient.parse_engine_path(path) + assert expected == actual + + +def test_example_path(): + project = "cuttlefish" + location = "mussel" + app = "winkle" + example = "nautilus" + expected = ( + "projects/{project}/locations/{location}/apps/{app}/examples/{example}".format( + project=project, + location=location, + app=app, + example=example, + ) + ) + actual = AgentServiceClient.example_path(project, location, app, example) + assert expected == actual + + +def test_parse_example_path(): + expected = { + "project": "scallop", + "location": "abalone", + "app": "squid", + "example": "clam", + } + path = AgentServiceClient.example_path(**expected) + + # Check that the path construction is reversible. + actual = AgentServiceClient.parse_example_path(path) + assert expected == actual + + +def test_guardrail_path(): + project = "whelk" + location = "octopus" + app = "oyster" + guardrail = "nudibranch" + expected = "projects/{project}/locations/{location}/apps/{app}/guardrails/{guardrail}".format( + project=project, + location=location, + app=app, + guardrail=guardrail, + ) + actual = AgentServiceClient.guardrail_path(project, location, app, guardrail) + assert expected == actual + + +def test_parse_guardrail_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "app": "winkle", + "guardrail": "nautilus", + } + path = AgentServiceClient.guardrail_path(**expected) + + # Check that the path construction is reversible. + actual = AgentServiceClient.parse_guardrail_path(path) + assert expected == actual + + +def test_inspect_template_path(): + organization = "scallop" + location = "abalone" + inspect_template = "squid" + expected = "organizations/{organization}/locations/{location}/inspectTemplates/{inspect_template}".format( + organization=organization, + location=location, + inspect_template=inspect_template, + ) + actual = AgentServiceClient.inspect_template_path( + organization, location, inspect_template + ) + assert expected == actual + + +def test_parse_inspect_template_path(): + expected = { + "organization": "clam", + "location": "whelk", + "inspect_template": "octopus", + } + path = AgentServiceClient.inspect_template_path(**expected) + + # Check that the path construction is reversible. + actual = AgentServiceClient.parse_inspect_template_path(path) + assert expected == actual + + +def test_secret_version_path(): + project = "oyster" + secret = "nudibranch" + secret_version = "cuttlefish" + expected = "projects/{project}/secrets/{secret}/versions/{secret_version}".format( + project=project, + secret=secret, + secret_version=secret_version, + ) + actual = AgentServiceClient.secret_version_path(project, secret, secret_version) + assert expected == actual + + +def test_parse_secret_version_path(): + expected = { + "project": "mussel", + "secret": "winkle", + "secret_version": "nautilus", + } + path = AgentServiceClient.secret_version_path(**expected) + + # Check that the path construction is reversible. + actual = AgentServiceClient.parse_secret_version_path(path) + assert expected == actual + + +def test_service_path(): + project = "scallop" + location = "abalone" + namespace = "squid" + service = "clam" + expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format( + project=project, + location=location, + namespace=namespace, + service=service, + ) + actual = AgentServiceClient.service_path(project, location, namespace, service) + assert expected == actual + + +def test_parse_service_path(): + expected = { + "project": "whelk", + "location": "octopus", + "namespace": "oyster", + "service": "nudibranch", + } + path = AgentServiceClient.service_path(**expected) + + # Check that the path construction is reversible. + actual = AgentServiceClient.parse_service_path(path) + assert expected == actual + + +def test_tool_path(): + project = "cuttlefish" + location = "mussel" + app = "winkle" + tool = "nautilus" + expected = "projects/{project}/locations/{location}/apps/{app}/tools/{tool}".format( + project=project, + location=location, + app=app, + tool=tool, + ) + actual = AgentServiceClient.tool_path(project, location, app, tool) + assert expected == actual + + +def test_parse_tool_path(): + expected = { + "project": "scallop", + "location": "abalone", + "app": "squid", + "tool": "clam", + } + path = AgentServiceClient.tool_path(**expected) + + # Check that the path construction is reversible. + actual = AgentServiceClient.parse_tool_path(path) + assert expected == actual + + +def test_toolset_path(): + project = "whelk" + location = "octopus" + app = "oyster" + toolset = "nudibranch" + expected = ( + "projects/{project}/locations/{location}/apps/{app}/toolsets/{toolset}".format( + project=project, + location=location, + app=app, + toolset=toolset, + ) + ) + actual = AgentServiceClient.toolset_path(project, location, app, toolset) + assert expected == actual + + +def test_parse_toolset_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "app": "winkle", + "toolset": "nautilus", + } + path = AgentServiceClient.toolset_path(**expected) + + # Check that the path construction is reversible. + actual = AgentServiceClient.parse_toolset_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = AgentServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = AgentServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = AgentServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = AgentServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = AgentServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AgentServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = AgentServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = AgentServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AgentServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format( + project=project, + ) + actual = AgentServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = AgentServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AgentServiceClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "cuttlefish" + location = "mussel" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = AgentServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = AgentServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = AgentServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.AgentServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.AgentServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = AgentServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_delete_operation(transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc_asyncio"): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_operation_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_delete_operation_from_dict(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc_asyncio"): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_cancel_operation_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_cancel_operation_from_dict(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_get_operation_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_get_operation_from_dict(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_list_operations_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_list_operations_from_dict(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_locations(transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc_asyncio"): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_list_locations_field_headers(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_locations_field_headers_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_list_locations_from_dict(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_location(transport: str = "grpc"): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + response = client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_get_location_field_headers(): + client = AgentServiceClient(credentials=ga_credentials.AnonymousCredentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() + + client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations/abc", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_location_field_headers_async(): + client = AgentServiceAsyncClient(credentials=async_anonymous_credentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations/abc", + ) in kw["metadata"] + + +def test_get_location_from_dict(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + response = client.get_location( + request={ + "name": "locations/abc", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_location_from_dict_async(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close_grpc(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = AgentServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "rest", + "grpc", + ] + for transport in transports: + client = AgentServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (AgentServiceClient, transports.AgentServiceGrpcTransport), + (AgentServiceAsyncClient, transports.AgentServiceGrpcAsyncIOTransport), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/packages/google-cloud-ces/tests/unit/gapic/ces_v1beta/test_evaluation_service.py b/packages/google-cloud-ces/tests/unit/gapic/ces_v1beta/test_evaluation_service.py new file mode 100644 index 000000000000..497d96ad5ae9 --- /dev/null +++ b/packages/google-cloud-ces/tests/unit/gapic/ces_v1beta/test_evaluation_service.py @@ -0,0 +1,30899 @@ +# -*- coding: utf-8 -*- +# 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. +# +import os + +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import json +import math +from collections.abc import AsyncIterable, Iterable, Mapping, Sequence + +import grpc +import pytest +from google.api_core import api_core_version +from google.protobuf import json_format +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +import google.api_core.operation_async as operation_async # type: ignore +import google.auth +import google.protobuf.any_pb2 as any_pb2 # type: ignore +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.struct_pb2 as struct_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore +from google.api_core import ( + client_options, + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + operation, + operations_v1, + path_template, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account + +from google.cloud.ces_v1beta.services.evaluation_service import ( + EvaluationServiceAsyncClient, + EvaluationServiceClient, + pagers, + transports, +) +from google.cloud.ces_v1beta.types import ( + app, + common, + evaluation, + evaluation_service, + example, + fakes, + golden_run, + session_service, + toolset_tool, +) +from google.cloud.ces_v1beta.types import conversation as gcc_conversation +from google.cloud.ces_v1beta.types import evaluation as gcc_evaluation + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert EvaluationServiceClient._get_default_mtls_endpoint(None) is None + assert ( + EvaluationServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + EvaluationServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + EvaluationServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + EvaluationServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + EvaluationServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + + +def test__read_environment_variables(): + assert EvaluationServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert EvaluationServiceClient._read_environment_variables() == ( + True, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert EvaluationServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with pytest.raises(ValueError) as excinfo: + EvaluationServiceClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + else: + assert EvaluationServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert EvaluationServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert EvaluationServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert EvaluationServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + EvaluationServiceClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert EvaluationServiceClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + + +def test_use_client_cert_effective(): + # Test case 1: Test when `should_use_client_cert` returns True. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch( + "google.auth.transport.mtls.should_use_client_cert", return_value=True + ): + assert EvaluationServiceClient._use_client_cert_effective() is True + + # Test case 2: Test when `should_use_client_cert` returns False. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should NOT be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch( + "google.auth.transport.mtls.should_use_client_cert", return_value=False + ): + assert EvaluationServiceClient._use_client_cert_effective() is False + + # Test case 3: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "true". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert EvaluationServiceClient._use_client_cert_effective() is True + + # Test case 4: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"} + ): + assert EvaluationServiceClient._use_client_cert_effective() is False + + # Test case 5: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "True". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "True"}): + assert EvaluationServiceClient._use_client_cert_effective() is True + + # Test case 6: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "False". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"} + ): + assert EvaluationServiceClient._use_client_cert_effective() is False + + # Test case 7: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "TRUE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "TRUE"}): + assert EvaluationServiceClient._use_client_cert_effective() is True + + # Test case 8: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "FALSE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"} + ): + assert EvaluationServiceClient._use_client_cert_effective() is False + + # Test case 9: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not set. + # In this case, the method should return False, which is the default value. + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, clear=True): + assert EvaluationServiceClient._use_client_cert_effective() is False + + # Test case 10: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should raise a ValueError as the environment variable must be either + # "true" or "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} + ): + with pytest.raises(ValueError): + EvaluationServiceClient._use_client_cert_effective() + + # Test case 11: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should return False as the environment variable is set to an invalid value. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} + ): + assert EvaluationServiceClient._use_client_cert_effective() is False + + # Test case 12: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is unset. Also, + # the GOOGLE_API_CONFIG environment variable is unset. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": ""}): + with mock.patch.dict(os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": ""}): + assert EvaluationServiceClient._use_client_cert_effective() is False + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert EvaluationServiceClient._get_client_cert_source(None, False) is None + assert ( + EvaluationServiceClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + EvaluationServiceClient._get_client_cert_source(mock_provided_cert_source, True) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + EvaluationServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + EvaluationServiceClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + EvaluationServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(EvaluationServiceClient), +) +@mock.patch.object( + EvaluationServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(EvaluationServiceAsyncClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = EvaluationServiceClient._DEFAULT_UNIVERSE + default_endpoint = EvaluationServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = EvaluationServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + EvaluationServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + EvaluationServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == EvaluationServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + EvaluationServiceClient._get_api_endpoint(None, None, default_universe, "auto") + == default_endpoint + ) + assert ( + EvaluationServiceClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == EvaluationServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + EvaluationServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == EvaluationServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + EvaluationServiceClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + EvaluationServiceClient._get_api_endpoint(None, None, default_universe, "never") + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + EvaluationServiceClient._get_api_endpoint( + None, mock_client_cert_source, mock_universe, "auto" + ) + assert ( + str(excinfo.value) + == "mTLS is not supported in any universe other than googleapis.com." + ) + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert ( + EvaluationServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + EvaluationServiceClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + EvaluationServiceClient._get_universe_domain(None, None) + == EvaluationServiceClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + EvaluationServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize( + "error_code,cred_info_json,show_cred_info", + [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False), + ], +) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = EvaluationServiceClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + + +@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = EvaluationServiceClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (EvaluationServiceClient, "grpc"), + (EvaluationServiceAsyncClient, "grpc_asyncio"), + (EvaluationServiceClient, "rest"), + ], +) +def test_evaluation_service_client_from_service_account_info( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "ces.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://ces.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.EvaluationServiceGrpcTransport, "grpc"), + (transports.EvaluationServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.EvaluationServiceRestTransport, "rest"), + ], +) +def test_evaluation_service_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (EvaluationServiceClient, "grpc"), + (EvaluationServiceAsyncClient, "grpc_asyncio"), + (EvaluationServiceClient, "rest"), + ], +) +def test_evaluation_service_client_from_service_account_file( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "ces.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://ces.googleapis.com" + ) + + +def test_evaluation_service_client_get_transport_class(): + transport = EvaluationServiceClient.get_transport_class() + available_transports = [ + transports.EvaluationServiceGrpcTransport, + transports.EvaluationServiceRestTransport, + ] + assert transport in available_transports + + transport = EvaluationServiceClient.get_transport_class("grpc") + assert transport == transports.EvaluationServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (EvaluationServiceClient, transports.EvaluationServiceGrpcTransport, "grpc"), + ( + EvaluationServiceAsyncClient, + transports.EvaluationServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (EvaluationServiceClient, transports.EvaluationServiceRestTransport, "rest"), + ], +) +@mock.patch.object( + EvaluationServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(EvaluationServiceClient), +) +@mock.patch.object( + EvaluationServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(EvaluationServiceAsyncClient), +) +def test_evaluation_service_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(EvaluationServiceClient, "get_transport_class") as gtc: + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(EvaluationServiceClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + EvaluationServiceClient, + transports.EvaluationServiceGrpcTransport, + "grpc", + "true", + ), + ( + EvaluationServiceAsyncClient, + transports.EvaluationServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + EvaluationServiceClient, + transports.EvaluationServiceGrpcTransport, + "grpc", + "false", + ), + ( + EvaluationServiceAsyncClient, + transports.EvaluationServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + EvaluationServiceClient, + transports.EvaluationServiceRestTransport, + "rest", + "true", + ), + ( + EvaluationServiceClient, + transports.EvaluationServiceRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + EvaluationServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(EvaluationServiceClient), +) +@mock.patch.object( + EvaluationServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(EvaluationServiceAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_evaluation_service_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class", [EvaluationServiceClient, EvaluationServiceAsyncClient] +) +@mock.patch.object( + EvaluationServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(EvaluationServiceClient), +) +@mock.patch.object( + EvaluationServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(EvaluationServiceAsyncClient), +) +def test_evaluation_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset. + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source() + ) + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + +@pytest.mark.parametrize( + "client_class", [EvaluationServiceClient, EvaluationServiceAsyncClient] +) +@mock.patch.object( + EvaluationServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(EvaluationServiceClient), +) +@mock.patch.object( + EvaluationServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(EvaluationServiceAsyncClient), +) +def test_evaluation_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = EvaluationServiceClient._DEFAULT_UNIVERSE + default_endpoint = EvaluationServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = EvaluationServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (EvaluationServiceClient, transports.EvaluationServiceGrpcTransport, "grpc"), + ( + EvaluationServiceAsyncClient, + transports.EvaluationServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (EvaluationServiceClient, transports.EvaluationServiceRestTransport, "rest"), + ], +) +def test_evaluation_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + EvaluationServiceClient, + transports.EvaluationServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + EvaluationServiceAsyncClient, + transports.EvaluationServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + EvaluationServiceClient, + transports.EvaluationServiceRestTransport, + "rest", + None, + ), + ], +) +def test_evaluation_service_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_evaluation_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.ces_v1beta.services.evaluation_service.transports.EvaluationServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = EvaluationServiceClient( + client_options={"api_endpoint": "squid.clam.whelk"} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + EvaluationServiceClient, + transports.EvaluationServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + EvaluationServiceAsyncClient, + transports.EvaluationServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_evaluation_service_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object(grpc_helpers, "create_channel") as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "ces.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + "https://www.googleapis.com/auth/ces", + "https://www.googleapis.com/auth/cloud-platform", + ), + scopes=None, + default_host="ces.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation.RunEvaluationRequest, + dict, + ], +) +def test_run_evaluation(request_type, transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.run_evaluation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.run_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = evaluation.RunEvaluationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_run_evaluation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = evaluation.RunEvaluationRequest( + app="app_value", + evaluation_dataset="evaluation_dataset_value", + display_name="display_name_value", + app_version="app_version_value", + scheduled_evaluation_run="scheduled_evaluation_run_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.run_evaluation), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.run_evaluation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation.RunEvaluationRequest( + app="app_value", + evaluation_dataset="evaluation_dataset_value", + display_name="display_name_value", + app_version="app_version_value", + scheduled_evaluation_run="scheduled_evaluation_run_value", + ) + + +def test_run_evaluation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.run_evaluation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.run_evaluation] = mock_rpc + request = {} + client.run_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.run_evaluation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_run_evaluation_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.run_evaluation + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.run_evaluation + ] = mock_rpc + + request = {} + await client.run_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.run_evaluation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_run_evaluation_async( + transport: str = "grpc_asyncio", request_type=evaluation.RunEvaluationRequest +): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.run_evaluation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.run_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = evaluation.RunEvaluationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_run_evaluation_async_from_dict(): + await test_run_evaluation_async(request_type=dict) + + +def test_run_evaluation_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation.RunEvaluationRequest() + + request.app = "app_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.run_evaluation), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.run_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "app=app_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_run_evaluation_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation.RunEvaluationRequest() + + request.app = "app_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.run_evaluation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.run_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "app=app_value", + ) in kw["metadata"] + + +def test_run_evaluation_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.run_evaluation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.run_evaluation( + app="app_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].app + mock_val = "app_value" + assert arg == mock_val + + +def test_run_evaluation_flattened_error(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.run_evaluation( + evaluation.RunEvaluationRequest(), + app="app_value", + ) + + +@pytest.mark.asyncio +async def test_run_evaluation_flattened_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.run_evaluation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.run_evaluation( + app="app_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].app + mock_val = "app_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_run_evaluation_flattened_error_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.run_evaluation( + evaluation.RunEvaluationRequest(), + app="app_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.UploadEvaluationAudioRequest, + dict, + ], +) +def test_upload_evaluation_audio(request_type, transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.upload_evaluation_audio), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_service.UploadEvaluationAudioResponse( + audio_gcs_uri="audio_gcs_uri_value", + audio_transcript="audio_transcript_value", + ) + response = client.upload_evaluation_audio(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = evaluation_service.UploadEvaluationAudioRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation_service.UploadEvaluationAudioResponse) + assert response.audio_gcs_uri == "audio_gcs_uri_value" + assert response.audio_transcript == "audio_transcript_value" + + +def test_upload_evaluation_audio_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = evaluation_service.UploadEvaluationAudioRequest( + app="app_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.upload_evaluation_audio), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.upload_evaluation_audio(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.UploadEvaluationAudioRequest( + app="app_value", + ) + + +def test_upload_evaluation_audio_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.upload_evaluation_audio + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.upload_evaluation_audio + ] = mock_rpc + request = {} + client.upload_evaluation_audio(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.upload_evaluation_audio(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_upload_evaluation_audio_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.upload_evaluation_audio + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.upload_evaluation_audio + ] = mock_rpc + + request = {} + await client.upload_evaluation_audio(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.upload_evaluation_audio(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_upload_evaluation_audio_async( + transport: str = "grpc_asyncio", + request_type=evaluation_service.UploadEvaluationAudioRequest, +): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.upload_evaluation_audio), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.UploadEvaluationAudioResponse( + audio_gcs_uri="audio_gcs_uri_value", + audio_transcript="audio_transcript_value", + ) + ) + response = await client.upload_evaluation_audio(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = evaluation_service.UploadEvaluationAudioRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation_service.UploadEvaluationAudioResponse) + assert response.audio_gcs_uri == "audio_gcs_uri_value" + assert response.audio_transcript == "audio_transcript_value" + + +@pytest.mark.asyncio +async def test_upload_evaluation_audio_async_from_dict(): + await test_upload_evaluation_audio_async(request_type=dict) + + +def test_upload_evaluation_audio_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.UploadEvaluationAudioRequest() + + request.app = "app_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.upload_evaluation_audio), "__call__" + ) as call: + call.return_value = evaluation_service.UploadEvaluationAudioResponse() + client.upload_evaluation_audio(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "app=app_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_upload_evaluation_audio_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.UploadEvaluationAudioRequest() + + request.app = "app_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.upload_evaluation_audio), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.UploadEvaluationAudioResponse() + ) + await client.upload_evaluation_audio(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "app=app_value", + ) in kw["metadata"] + + +def test_upload_evaluation_audio_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.upload_evaluation_audio), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_service.UploadEvaluationAudioResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.upload_evaluation_audio( + app="app_value", + audio_content=b"audio_content_blob", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].app + mock_val = "app_value" + assert arg == mock_val + arg = args[0].audio_content + mock_val = b"audio_content_blob" + assert arg == mock_val + + +def test_upload_evaluation_audio_flattened_error(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.upload_evaluation_audio( + evaluation_service.UploadEvaluationAudioRequest(), + app="app_value", + audio_content=b"audio_content_blob", + ) + + +@pytest.mark.asyncio +async def test_upload_evaluation_audio_flattened_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.upload_evaluation_audio), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_service.UploadEvaluationAudioResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.UploadEvaluationAudioResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.upload_evaluation_audio( + app="app_value", + audio_content=b"audio_content_blob", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].app + mock_val = "app_value" + assert arg == mock_val + arg = args[0].audio_content + mock_val = b"audio_content_blob" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_upload_evaluation_audio_flattened_error_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.upload_evaluation_audio( + evaluation_service.UploadEvaluationAudioRequest(), + app="app_value", + audio_content=b"audio_content_blob", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.CreateEvaluationRequest, + dict, + ], +) +def test_create_evaluation(request_type, transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_evaluation.Evaluation( + name="name_value", + display_name="display_name_value", + description="description_value", + tags=["tags_value"], + evaluation_datasets=["evaluation_datasets_value"], + created_by="created_by_value", + last_updated_by="last_updated_by_value", + evaluation_runs=["evaluation_runs_value"], + etag="etag_value", + invalid=True, + ) + response = client.create_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = evaluation_service.CreateEvaluationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_evaluation.Evaluation) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.tags == ["tags_value"] + assert response.evaluation_datasets == ["evaluation_datasets_value"] + assert response.created_by == "created_by_value" + assert response.last_updated_by == "last_updated_by_value" + assert response.evaluation_runs == ["evaluation_runs_value"] + assert response.etag == "etag_value" + assert response.invalid is True + + +def test_create_evaluation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = evaluation_service.CreateEvaluationRequest( + parent="parent_value", + evaluation_id="evaluation_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_evaluation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.CreateEvaluationRequest( + parent="parent_value", + evaluation_id="evaluation_id_value", + ) + + +def test_create_evaluation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_evaluation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_evaluation] = ( + mock_rpc + ) + request = {} + client.create_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_evaluation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_evaluation_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_evaluation + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_evaluation + ] = mock_rpc + + request = {} + await client.create_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_evaluation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_evaluation_async( + transport: str = "grpc_asyncio", + request_type=evaluation_service.CreateEvaluationRequest, +): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_evaluation.Evaluation( + name="name_value", + display_name="display_name_value", + description="description_value", + tags=["tags_value"], + evaluation_datasets=["evaluation_datasets_value"], + created_by="created_by_value", + last_updated_by="last_updated_by_value", + evaluation_runs=["evaluation_runs_value"], + etag="etag_value", + invalid=True, + ) + ) + response = await client.create_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = evaluation_service.CreateEvaluationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_evaluation.Evaluation) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.tags == ["tags_value"] + assert response.evaluation_datasets == ["evaluation_datasets_value"] + assert response.created_by == "created_by_value" + assert response.last_updated_by == "last_updated_by_value" + assert response.evaluation_runs == ["evaluation_runs_value"] + assert response.etag == "etag_value" + assert response.invalid is True + + +@pytest.mark.asyncio +async def test_create_evaluation_async_from_dict(): + await test_create_evaluation_async(request_type=dict) + + +def test_create_evaluation_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.CreateEvaluationRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation), "__call__" + ) as call: + call.return_value = gcc_evaluation.Evaluation() + client.create_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_evaluation_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.CreateEvaluationRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_evaluation.Evaluation() + ) + await client.create_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_evaluation_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_evaluation.Evaluation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_evaluation( + parent="parent_value", + evaluation=gcc_evaluation.Evaluation( + golden=gcc_evaluation.Evaluation.Golden( + turns=[ + gcc_evaluation.Evaluation.GoldenTurn( + steps=[ + gcc_evaluation.Evaluation.Step( + user_input=session_service.SessionInput( + text="text_value" + ) + ) + ] + ) + ] + ) + ), + evaluation_id="evaluation_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].evaluation + mock_val = gcc_evaluation.Evaluation( + golden=gcc_evaluation.Evaluation.Golden( + turns=[ + gcc_evaluation.Evaluation.GoldenTurn( + steps=[ + gcc_evaluation.Evaluation.Step( + user_input=session_service.SessionInput( + text="text_value" + ) + ) + ] + ) + ] + ) + ) + assert arg == mock_val + arg = args[0].evaluation_id + mock_val = "evaluation_id_value" + assert arg == mock_val + + +def test_create_evaluation_flattened_error(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_evaluation( + evaluation_service.CreateEvaluationRequest(), + parent="parent_value", + evaluation=gcc_evaluation.Evaluation( + golden=gcc_evaluation.Evaluation.Golden( + turns=[ + gcc_evaluation.Evaluation.GoldenTurn( + steps=[ + gcc_evaluation.Evaluation.Step( + user_input=session_service.SessionInput( + text="text_value" + ) + ) + ] + ) + ] + ) + ), + evaluation_id="evaluation_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_evaluation_flattened_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_evaluation.Evaluation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_evaluation.Evaluation() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_evaluation( + parent="parent_value", + evaluation=gcc_evaluation.Evaluation( + golden=gcc_evaluation.Evaluation.Golden( + turns=[ + gcc_evaluation.Evaluation.GoldenTurn( + steps=[ + gcc_evaluation.Evaluation.Step( + user_input=session_service.SessionInput( + text="text_value" + ) + ) + ] + ) + ] + ) + ), + evaluation_id="evaluation_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].evaluation + mock_val = gcc_evaluation.Evaluation( + golden=gcc_evaluation.Evaluation.Golden( + turns=[ + gcc_evaluation.Evaluation.GoldenTurn( + steps=[ + gcc_evaluation.Evaluation.Step( + user_input=session_service.SessionInput( + text="text_value" + ) + ) + ] + ) + ] + ) + ) + assert arg == mock_val + arg = args[0].evaluation_id + mock_val = "evaluation_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_evaluation_flattened_error_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_evaluation( + evaluation_service.CreateEvaluationRequest(), + parent="parent_value", + evaluation=gcc_evaluation.Evaluation( + golden=gcc_evaluation.Evaluation.Golden( + turns=[ + gcc_evaluation.Evaluation.GoldenTurn( + steps=[ + gcc_evaluation.Evaluation.Step( + user_input=session_service.SessionInput( + text="text_value" + ) + ) + ] + ) + ] + ) + ), + evaluation_id="evaluation_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.GenerateEvaluationRequest, + dict, + ], +) +def test_generate_evaluation(request_type, transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_evaluation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.generate_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = evaluation_service.GenerateEvaluationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_generate_evaluation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = evaluation_service.GenerateEvaluationRequest( + conversation="conversation_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_evaluation), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.generate_evaluation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.GenerateEvaluationRequest( + conversation="conversation_value", + ) + + +def test_generate_evaluation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.generate_evaluation in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.generate_evaluation] = ( + mock_rpc + ) + request = {} + client.generate_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.generate_evaluation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_generate_evaluation_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.generate_evaluation + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.generate_evaluation + ] = mock_rpc + + request = {} + await client.generate_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.generate_evaluation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_generate_evaluation_async( + transport: str = "grpc_asyncio", + request_type=evaluation_service.GenerateEvaluationRequest, +): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_evaluation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.generate_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = evaluation_service.GenerateEvaluationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_generate_evaluation_async_from_dict(): + await test_generate_evaluation_async(request_type=dict) + + +def test_generate_evaluation_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.GenerateEvaluationRequest() + + request.conversation = "conversation_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_evaluation), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.generate_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "conversation=conversation_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_generate_evaluation_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.GenerateEvaluationRequest() + + request.conversation = "conversation_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_evaluation), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.generate_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "conversation=conversation_value", + ) in kw["metadata"] + + +def test_generate_evaluation_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_evaluation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.generate_evaluation( + conversation="conversation_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].conversation + mock_val = "conversation_value" + assert arg == mock_val + + +def test_generate_evaluation_flattened_error(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.generate_evaluation( + evaluation_service.GenerateEvaluationRequest(), + conversation="conversation_value", + ) + + +@pytest.mark.asyncio +async def test_generate_evaluation_flattened_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_evaluation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.generate_evaluation( + conversation="conversation_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].conversation + mock_val = "conversation_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_generate_evaluation_flattened_error_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.generate_evaluation( + evaluation_service.GenerateEvaluationRequest(), + conversation="conversation_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.ImportEvaluationsRequest, + dict, + ], +) +def test_import_evaluations(request_type, transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_evaluations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.import_evaluations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = evaluation_service.ImportEvaluationsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_evaluations_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = evaluation_service.ImportEvaluationsRequest( + gcs_uri="gcs_uri_value", + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_evaluations), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.import_evaluations(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.ImportEvaluationsRequest( + gcs_uri="gcs_uri_value", + parent="parent_value", + ) + + +def test_import_evaluations_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.import_evaluations in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.import_evaluations] = ( + mock_rpc + ) + request = {} + client.import_evaluations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.import_evaluations(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_import_evaluations_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.import_evaluations + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.import_evaluations + ] = mock_rpc + + request = {} + await client.import_evaluations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.import_evaluations(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_import_evaluations_async( + transport: str = "grpc_asyncio", + request_type=evaluation_service.ImportEvaluationsRequest, +): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_evaluations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.import_evaluations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = evaluation_service.ImportEvaluationsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_import_evaluations_async_from_dict(): + await test_import_evaluations_async(request_type=dict) + + +def test_import_evaluations_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.ImportEvaluationsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_evaluations), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.import_evaluations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_import_evaluations_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.ImportEvaluationsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_evaluations), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.import_evaluations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_import_evaluations_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_evaluations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.import_evaluations( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_import_evaluations_flattened_error(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.import_evaluations( + evaluation_service.ImportEvaluationsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_import_evaluations_flattened_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_evaluations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.import_evaluations( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_import_evaluations_flattened_error_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.import_evaluations( + evaluation_service.ImportEvaluationsRequest(), + parent="parent_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.CreateEvaluationDatasetRequest, + dict, + ], +) +def test_create_evaluation_dataset(request_type, transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation_dataset), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.EvaluationDataset( + name="name_value", + display_name="display_name_value", + evaluations=["evaluations_value"], + etag="etag_value", + created_by="created_by_value", + last_updated_by="last_updated_by_value", + ) + response = client.create_evaluation_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = evaluation_service.CreateEvaluationDatasetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.EvaluationDataset) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.evaluations == ["evaluations_value"] + assert response.etag == "etag_value" + assert response.created_by == "created_by_value" + assert response.last_updated_by == "last_updated_by_value" + + +def test_create_evaluation_dataset_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = evaluation_service.CreateEvaluationDatasetRequest( + parent="parent_value", + evaluation_dataset_id="evaluation_dataset_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation_dataset), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_evaluation_dataset(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.CreateEvaluationDatasetRequest( + parent="parent_value", + evaluation_dataset_id="evaluation_dataset_id_value", + ) + + +def test_create_evaluation_dataset_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_evaluation_dataset + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_evaluation_dataset + ] = mock_rpc + request = {} + client.create_evaluation_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_evaluation_dataset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_evaluation_dataset_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_evaluation_dataset + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_evaluation_dataset + ] = mock_rpc + + request = {} + await client.create_evaluation_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_evaluation_dataset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_evaluation_dataset_async( + transport: str = "grpc_asyncio", + request_type=evaluation_service.CreateEvaluationDatasetRequest, +): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation_dataset), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.EvaluationDataset( + name="name_value", + display_name="display_name_value", + evaluations=["evaluations_value"], + etag="etag_value", + created_by="created_by_value", + last_updated_by="last_updated_by_value", + ) + ) + response = await client.create_evaluation_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = evaluation_service.CreateEvaluationDatasetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.EvaluationDataset) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.evaluations == ["evaluations_value"] + assert response.etag == "etag_value" + assert response.created_by == "created_by_value" + assert response.last_updated_by == "last_updated_by_value" + + +@pytest.mark.asyncio +async def test_create_evaluation_dataset_async_from_dict(): + await test_create_evaluation_dataset_async(request_type=dict) + + +def test_create_evaluation_dataset_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.CreateEvaluationDatasetRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation_dataset), "__call__" + ) as call: + call.return_value = evaluation.EvaluationDataset() + client.create_evaluation_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_evaluation_dataset_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.CreateEvaluationDatasetRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation_dataset), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.EvaluationDataset() + ) + await client.create_evaluation_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_evaluation_dataset_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation_dataset), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.EvaluationDataset() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_evaluation_dataset( + parent="parent_value", + evaluation_dataset=evaluation.EvaluationDataset(name="name_value"), + evaluation_dataset_id="evaluation_dataset_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].evaluation_dataset + mock_val = evaluation.EvaluationDataset(name="name_value") + assert arg == mock_val + arg = args[0].evaluation_dataset_id + mock_val = "evaluation_dataset_id_value" + assert arg == mock_val + + +def test_create_evaluation_dataset_flattened_error(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_evaluation_dataset( + evaluation_service.CreateEvaluationDatasetRequest(), + parent="parent_value", + evaluation_dataset=evaluation.EvaluationDataset(name="name_value"), + evaluation_dataset_id="evaluation_dataset_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_evaluation_dataset_flattened_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation_dataset), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.EvaluationDataset() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.EvaluationDataset() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_evaluation_dataset( + parent="parent_value", + evaluation_dataset=evaluation.EvaluationDataset(name="name_value"), + evaluation_dataset_id="evaluation_dataset_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].evaluation_dataset + mock_val = evaluation.EvaluationDataset(name="name_value") + assert arg == mock_val + arg = args[0].evaluation_dataset_id + mock_val = "evaluation_dataset_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_evaluation_dataset_flattened_error_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_evaluation_dataset( + evaluation_service.CreateEvaluationDatasetRequest(), + parent="parent_value", + evaluation_dataset=evaluation.EvaluationDataset(name="name_value"), + evaluation_dataset_id="evaluation_dataset_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.UpdateEvaluationRequest, + dict, + ], +) +def test_update_evaluation(request_type, transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_evaluation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_evaluation.Evaluation( + name="name_value", + display_name="display_name_value", + description="description_value", + tags=["tags_value"], + evaluation_datasets=["evaluation_datasets_value"], + created_by="created_by_value", + last_updated_by="last_updated_by_value", + evaluation_runs=["evaluation_runs_value"], + etag="etag_value", + invalid=True, + ) + response = client.update_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = evaluation_service.UpdateEvaluationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_evaluation.Evaluation) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.tags == ["tags_value"] + assert response.evaluation_datasets == ["evaluation_datasets_value"] + assert response.created_by == "created_by_value" + assert response.last_updated_by == "last_updated_by_value" + assert response.evaluation_runs == ["evaluation_runs_value"] + assert response.etag == "etag_value" + assert response.invalid is True + + +def test_update_evaluation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = evaluation_service.UpdateEvaluationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_evaluation), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_evaluation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.UpdateEvaluationRequest() + + +def test_update_evaluation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_evaluation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_evaluation] = ( + mock_rpc + ) + request = {} + client.update_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_evaluation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_evaluation_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_evaluation + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_evaluation + ] = mock_rpc + + request = {} + await client.update_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_evaluation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_evaluation_async( + transport: str = "grpc_asyncio", + request_type=evaluation_service.UpdateEvaluationRequest, +): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_evaluation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_evaluation.Evaluation( + name="name_value", + display_name="display_name_value", + description="description_value", + tags=["tags_value"], + evaluation_datasets=["evaluation_datasets_value"], + created_by="created_by_value", + last_updated_by="last_updated_by_value", + evaluation_runs=["evaluation_runs_value"], + etag="etag_value", + invalid=True, + ) + ) + response = await client.update_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = evaluation_service.UpdateEvaluationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_evaluation.Evaluation) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.tags == ["tags_value"] + assert response.evaluation_datasets == ["evaluation_datasets_value"] + assert response.created_by == "created_by_value" + assert response.last_updated_by == "last_updated_by_value" + assert response.evaluation_runs == ["evaluation_runs_value"] + assert response.etag == "etag_value" + assert response.invalid is True + + +@pytest.mark.asyncio +async def test_update_evaluation_async_from_dict(): + await test_update_evaluation_async(request_type=dict) + + +def test_update_evaluation_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.UpdateEvaluationRequest() + + request.evaluation.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_evaluation), "__call__" + ) as call: + call.return_value = gcc_evaluation.Evaluation() + client.update_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "evaluation.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_evaluation_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.UpdateEvaluationRequest() + + request.evaluation.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_evaluation), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_evaluation.Evaluation() + ) + await client.update_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "evaluation.name=name_value", + ) in kw["metadata"] + + +def test_update_evaluation_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_evaluation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_evaluation.Evaluation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_evaluation( + evaluation=gcc_evaluation.Evaluation( + golden=gcc_evaluation.Evaluation.Golden( + turns=[ + gcc_evaluation.Evaluation.GoldenTurn( + steps=[ + gcc_evaluation.Evaluation.Step( + user_input=session_service.SessionInput( + text="text_value" + ) + ) + ] + ) + ] + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].evaluation + mock_val = gcc_evaluation.Evaluation( + golden=gcc_evaluation.Evaluation.Golden( + turns=[ + gcc_evaluation.Evaluation.GoldenTurn( + steps=[ + gcc_evaluation.Evaluation.Step( + user_input=session_service.SessionInput( + text="text_value" + ) + ) + ] + ) + ] + ) + ) + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_evaluation_flattened_error(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_evaluation( + evaluation_service.UpdateEvaluationRequest(), + evaluation=gcc_evaluation.Evaluation( + golden=gcc_evaluation.Evaluation.Golden( + turns=[ + gcc_evaluation.Evaluation.GoldenTurn( + steps=[ + gcc_evaluation.Evaluation.Step( + user_input=session_service.SessionInput( + text="text_value" + ) + ) + ] + ) + ] + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_evaluation_flattened_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_evaluation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = gcc_evaluation.Evaluation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_evaluation.Evaluation() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_evaluation( + evaluation=gcc_evaluation.Evaluation( + golden=gcc_evaluation.Evaluation.Golden( + turns=[ + gcc_evaluation.Evaluation.GoldenTurn( + steps=[ + gcc_evaluation.Evaluation.Step( + user_input=session_service.SessionInput( + text="text_value" + ) + ) + ] + ) + ] + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].evaluation + mock_val = gcc_evaluation.Evaluation( + golden=gcc_evaluation.Evaluation.Golden( + turns=[ + gcc_evaluation.Evaluation.GoldenTurn( + steps=[ + gcc_evaluation.Evaluation.Step( + user_input=session_service.SessionInput( + text="text_value" + ) + ) + ] + ) + ] + ) + ) + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_evaluation_flattened_error_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_evaluation( + evaluation_service.UpdateEvaluationRequest(), + evaluation=gcc_evaluation.Evaluation( + golden=gcc_evaluation.Evaluation.Golden( + turns=[ + gcc_evaluation.Evaluation.GoldenTurn( + steps=[ + gcc_evaluation.Evaluation.Step( + user_input=session_service.SessionInput( + text="text_value" + ) + ) + ] + ) + ] + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.UpdateEvaluationDatasetRequest, + dict, + ], +) +def test_update_evaluation_dataset(request_type, transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_evaluation_dataset), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.EvaluationDataset( + name="name_value", + display_name="display_name_value", + evaluations=["evaluations_value"], + etag="etag_value", + created_by="created_by_value", + last_updated_by="last_updated_by_value", + ) + response = client.update_evaluation_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = evaluation_service.UpdateEvaluationDatasetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.EvaluationDataset) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.evaluations == ["evaluations_value"] + assert response.etag == "etag_value" + assert response.created_by == "created_by_value" + assert response.last_updated_by == "last_updated_by_value" + + +def test_update_evaluation_dataset_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = evaluation_service.UpdateEvaluationDatasetRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_evaluation_dataset), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_evaluation_dataset(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.UpdateEvaluationDatasetRequest() + + +def test_update_evaluation_dataset_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_evaluation_dataset + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_evaluation_dataset + ] = mock_rpc + request = {} + client.update_evaluation_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_evaluation_dataset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_evaluation_dataset_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_evaluation_dataset + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_evaluation_dataset + ] = mock_rpc + + request = {} + await client.update_evaluation_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_evaluation_dataset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_evaluation_dataset_async( + transport: str = "grpc_asyncio", + request_type=evaluation_service.UpdateEvaluationDatasetRequest, +): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_evaluation_dataset), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.EvaluationDataset( + name="name_value", + display_name="display_name_value", + evaluations=["evaluations_value"], + etag="etag_value", + created_by="created_by_value", + last_updated_by="last_updated_by_value", + ) + ) + response = await client.update_evaluation_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = evaluation_service.UpdateEvaluationDatasetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.EvaluationDataset) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.evaluations == ["evaluations_value"] + assert response.etag == "etag_value" + assert response.created_by == "created_by_value" + assert response.last_updated_by == "last_updated_by_value" + + +@pytest.mark.asyncio +async def test_update_evaluation_dataset_async_from_dict(): + await test_update_evaluation_dataset_async(request_type=dict) + + +def test_update_evaluation_dataset_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.UpdateEvaluationDatasetRequest() + + request.evaluation_dataset.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_evaluation_dataset), "__call__" + ) as call: + call.return_value = evaluation.EvaluationDataset() + client.update_evaluation_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "evaluation_dataset.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_evaluation_dataset_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.UpdateEvaluationDatasetRequest() + + request.evaluation_dataset.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_evaluation_dataset), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.EvaluationDataset() + ) + await client.update_evaluation_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "evaluation_dataset.name=name_value", + ) in kw["metadata"] + + +def test_update_evaluation_dataset_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_evaluation_dataset), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.EvaluationDataset() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_evaluation_dataset( + evaluation_dataset=evaluation.EvaluationDataset(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].evaluation_dataset + mock_val = evaluation.EvaluationDataset(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_evaluation_dataset_flattened_error(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_evaluation_dataset( + evaluation_service.UpdateEvaluationDatasetRequest(), + evaluation_dataset=evaluation.EvaluationDataset(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_evaluation_dataset_flattened_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_evaluation_dataset), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.EvaluationDataset() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.EvaluationDataset() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_evaluation_dataset( + evaluation_dataset=evaluation.EvaluationDataset(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].evaluation_dataset + mock_val = evaluation.EvaluationDataset(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_evaluation_dataset_flattened_error_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_evaluation_dataset( + evaluation_service.UpdateEvaluationDatasetRequest(), + evaluation_dataset=evaluation.EvaluationDataset(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.DeleteEvaluationRequest, + dict, + ], +) +def test_delete_evaluation(request_type, transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = evaluation_service.DeleteEvaluationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_evaluation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = evaluation_service.DeleteEvaluationRequest( + name="name_value", + etag="etag_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_evaluation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.DeleteEvaluationRequest( + name="name_value", + etag="etag_value", + ) + + +def test_delete_evaluation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_evaluation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_evaluation] = ( + mock_rpc + ) + request = {} + client.delete_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_evaluation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_evaluation_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_evaluation + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_evaluation + ] = mock_rpc + + request = {} + await client.delete_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_evaluation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_evaluation_async( + transport: str = "grpc_asyncio", + request_type=evaluation_service.DeleteEvaluationRequest, +): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = evaluation_service.DeleteEvaluationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_evaluation_async_from_dict(): + await test_delete_evaluation_async(request_type=dict) + + +def test_delete_evaluation_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.DeleteEvaluationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation), "__call__" + ) as call: + call.return_value = None + client.delete_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_evaluation_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.DeleteEvaluationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_evaluation_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_evaluation( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_evaluation_flattened_error(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_evaluation( + evaluation_service.DeleteEvaluationRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_evaluation_flattened_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_evaluation( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_evaluation_flattened_error_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_evaluation( + evaluation_service.DeleteEvaluationRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.DeleteEvaluationResultRequest, + dict, + ], +) +def test_delete_evaluation_result(request_type, transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_result), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_evaluation_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = evaluation_service.DeleteEvaluationResultRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_evaluation_result_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = evaluation_service.DeleteEvaluationResultRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_result), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_evaluation_result(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.DeleteEvaluationResultRequest( + name="name_value", + ) + + +def test_delete_evaluation_result_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_evaluation_result + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_evaluation_result + ] = mock_rpc + request = {} + client.delete_evaluation_result(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_evaluation_result(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_evaluation_result_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_evaluation_result + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_evaluation_result + ] = mock_rpc + + request = {} + await client.delete_evaluation_result(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_evaluation_result(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_evaluation_result_async( + transport: str = "grpc_asyncio", + request_type=evaluation_service.DeleteEvaluationResultRequest, +): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_result), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_evaluation_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = evaluation_service.DeleteEvaluationResultRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_evaluation_result_async_from_dict(): + await test_delete_evaluation_result_async(request_type=dict) + + +def test_delete_evaluation_result_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.DeleteEvaluationResultRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_result), "__call__" + ) as call: + call.return_value = None + client.delete_evaluation_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_evaluation_result_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.DeleteEvaluationResultRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_result), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_evaluation_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_evaluation_result_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_result), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_evaluation_result( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_evaluation_result_flattened_error(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_evaluation_result( + evaluation_service.DeleteEvaluationResultRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_evaluation_result_flattened_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_result), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_evaluation_result( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_evaluation_result_flattened_error_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_evaluation_result( + evaluation_service.DeleteEvaluationResultRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.DeleteEvaluationDatasetRequest, + dict, + ], +) +def test_delete_evaluation_dataset(request_type, transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_dataset), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_evaluation_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = evaluation_service.DeleteEvaluationDatasetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_evaluation_dataset_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = evaluation_service.DeleteEvaluationDatasetRequest( + name="name_value", + etag="etag_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_dataset), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_evaluation_dataset(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.DeleteEvaluationDatasetRequest( + name="name_value", + etag="etag_value", + ) + + +def test_delete_evaluation_dataset_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_evaluation_dataset + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_evaluation_dataset + ] = mock_rpc + request = {} + client.delete_evaluation_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_evaluation_dataset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_evaluation_dataset_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_evaluation_dataset + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_evaluation_dataset + ] = mock_rpc + + request = {} + await client.delete_evaluation_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_evaluation_dataset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_evaluation_dataset_async( + transport: str = "grpc_asyncio", + request_type=evaluation_service.DeleteEvaluationDatasetRequest, +): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_dataset), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_evaluation_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = evaluation_service.DeleteEvaluationDatasetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_evaluation_dataset_async_from_dict(): + await test_delete_evaluation_dataset_async(request_type=dict) + + +def test_delete_evaluation_dataset_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.DeleteEvaluationDatasetRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_dataset), "__call__" + ) as call: + call.return_value = None + client.delete_evaluation_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_evaluation_dataset_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.DeleteEvaluationDatasetRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_dataset), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_evaluation_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_evaluation_dataset_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_dataset), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_evaluation_dataset( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_evaluation_dataset_flattened_error(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_evaluation_dataset( + evaluation_service.DeleteEvaluationDatasetRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_evaluation_dataset_flattened_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_dataset), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_evaluation_dataset( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_evaluation_dataset_flattened_error_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_evaluation_dataset( + evaluation_service.DeleteEvaluationDatasetRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.DeleteEvaluationRunRequest, + dict, + ], +) +def test_delete_evaluation_run(request_type, transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_run), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = evaluation_service.DeleteEvaluationRunRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_evaluation_run_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = evaluation_service.DeleteEvaluationRunRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_run), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_evaluation_run(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.DeleteEvaluationRunRequest( + name="name_value", + ) + + +def test_delete_evaluation_run_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_evaluation_run + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_evaluation_run] = ( + mock_rpc + ) + request = {} + client.delete_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_evaluation_run(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_evaluation_run_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_evaluation_run + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_evaluation_run + ] = mock_rpc + + request = {} + await client.delete_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_evaluation_run(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_evaluation_run_async( + transport: str = "grpc_asyncio", + request_type=evaluation_service.DeleteEvaluationRunRequest, +): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_run), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.delete_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = evaluation_service.DeleteEvaluationRunRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_evaluation_run_async_from_dict(): + await test_delete_evaluation_run_async(request_type=dict) + + +def test_delete_evaluation_run_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.DeleteEvaluationRunRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_run), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_evaluation_run_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.DeleteEvaluationRunRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_run), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.delete_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_evaluation_run_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_run), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_evaluation_run( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_evaluation_run_flattened_error(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_evaluation_run( + evaluation_service.DeleteEvaluationRunRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_evaluation_run_flattened_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_run), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_evaluation_run( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_evaluation_run_flattened_error_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_evaluation_run( + evaluation_service.DeleteEvaluationRunRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.GetEvaluationRequest, + dict, + ], +) +def test_get_evaluation(request_type, transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_evaluation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.Evaluation( + name="name_value", + display_name="display_name_value", + description="description_value", + tags=["tags_value"], + evaluation_datasets=["evaluation_datasets_value"], + created_by="created_by_value", + last_updated_by="last_updated_by_value", + evaluation_runs=["evaluation_runs_value"], + etag="etag_value", + invalid=True, + ) + response = client.get_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = evaluation_service.GetEvaluationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.Evaluation) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.tags == ["tags_value"] + assert response.evaluation_datasets == ["evaluation_datasets_value"] + assert response.created_by == "created_by_value" + assert response.last_updated_by == "last_updated_by_value" + assert response.evaluation_runs == ["evaluation_runs_value"] + assert response.etag == "etag_value" + assert response.invalid is True + + +def test_get_evaluation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = evaluation_service.GetEvaluationRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_evaluation), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_evaluation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.GetEvaluationRequest( + name="name_value", + ) + + +def test_get_evaluation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_evaluation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_evaluation] = mock_rpc + request = {} + client.get_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_evaluation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_evaluation_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_evaluation + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_evaluation + ] = mock_rpc + + request = {} + await client.get_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_evaluation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_evaluation_async( + transport: str = "grpc_asyncio", + request_type=evaluation_service.GetEvaluationRequest, +): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_evaluation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.Evaluation( + name="name_value", + display_name="display_name_value", + description="description_value", + tags=["tags_value"], + evaluation_datasets=["evaluation_datasets_value"], + created_by="created_by_value", + last_updated_by="last_updated_by_value", + evaluation_runs=["evaluation_runs_value"], + etag="etag_value", + invalid=True, + ) + ) + response = await client.get_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = evaluation_service.GetEvaluationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.Evaluation) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.tags == ["tags_value"] + assert response.evaluation_datasets == ["evaluation_datasets_value"] + assert response.created_by == "created_by_value" + assert response.last_updated_by == "last_updated_by_value" + assert response.evaluation_runs == ["evaluation_runs_value"] + assert response.etag == "etag_value" + assert response.invalid is True + + +@pytest.mark.asyncio +async def test_get_evaluation_async_from_dict(): + await test_get_evaluation_async(request_type=dict) + + +def test_get_evaluation_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.GetEvaluationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_evaluation), "__call__") as call: + call.return_value = evaluation.Evaluation() + client.get_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_evaluation_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.GetEvaluationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_evaluation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.Evaluation() + ) + await client.get_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_evaluation_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_evaluation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.Evaluation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_evaluation( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_evaluation_flattened_error(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_evaluation( + evaluation_service.GetEvaluationRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_evaluation_flattened_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_evaluation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.Evaluation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.Evaluation() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_evaluation( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_evaluation_flattened_error_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_evaluation( + evaluation_service.GetEvaluationRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.GetEvaluationResultRequest, + dict, + ], +) +def test_get_evaluation_result(request_type, transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_evaluation_result), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.EvaluationResult( + name="name_value", + display_name="display_name_value", + evaluation_status=evaluation.EvaluationResult.Outcome.PASS, + evaluation_run="evaluation_run_value", + initiated_by="initiated_by_value", + app_version="app_version_value", + app_version_display_name="app_version_display_name_value", + changelog="changelog_value", + execution_state=evaluation.EvaluationResult.ExecutionState.RUNNING, + golden_run_method=golden_run.GoldenRunMethod.STABLE, + ) + response = client.get_evaluation_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = evaluation_service.GetEvaluationResultRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.EvaluationResult) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.evaluation_status == evaluation.EvaluationResult.Outcome.PASS + assert response.evaluation_run == "evaluation_run_value" + assert response.initiated_by == "initiated_by_value" + assert response.app_version == "app_version_value" + assert response.app_version_display_name == "app_version_display_name_value" + assert response.changelog == "changelog_value" + assert ( + response.execution_state == evaluation.EvaluationResult.ExecutionState.RUNNING + ) + assert response.golden_run_method == golden_run.GoldenRunMethod.STABLE + + +def test_get_evaluation_result_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = evaluation_service.GetEvaluationResultRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_evaluation_result), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_evaluation_result(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.GetEvaluationResultRequest( + name="name_value", + ) + + +def test_get_evaluation_result_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_evaluation_result + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_evaluation_result] = ( + mock_rpc + ) + request = {} + client.get_evaluation_result(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_evaluation_result(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_evaluation_result_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_evaluation_result + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_evaluation_result + ] = mock_rpc + + request = {} + await client.get_evaluation_result(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_evaluation_result(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_evaluation_result_async( + transport: str = "grpc_asyncio", + request_type=evaluation_service.GetEvaluationResultRequest, +): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_evaluation_result), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.EvaluationResult( + name="name_value", + display_name="display_name_value", + evaluation_status=evaluation.EvaluationResult.Outcome.PASS, + evaluation_run="evaluation_run_value", + initiated_by="initiated_by_value", + app_version="app_version_value", + app_version_display_name="app_version_display_name_value", + changelog="changelog_value", + execution_state=evaluation.EvaluationResult.ExecutionState.RUNNING, + golden_run_method=golden_run.GoldenRunMethod.STABLE, + ) + ) + response = await client.get_evaluation_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = evaluation_service.GetEvaluationResultRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.EvaluationResult) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.evaluation_status == evaluation.EvaluationResult.Outcome.PASS + assert response.evaluation_run == "evaluation_run_value" + assert response.initiated_by == "initiated_by_value" + assert response.app_version == "app_version_value" + assert response.app_version_display_name == "app_version_display_name_value" + assert response.changelog == "changelog_value" + assert ( + response.execution_state == evaluation.EvaluationResult.ExecutionState.RUNNING + ) + assert response.golden_run_method == golden_run.GoldenRunMethod.STABLE + + +@pytest.mark.asyncio +async def test_get_evaluation_result_async_from_dict(): + await test_get_evaluation_result_async(request_type=dict) + + +def test_get_evaluation_result_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.GetEvaluationResultRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_evaluation_result), "__call__" + ) as call: + call.return_value = evaluation.EvaluationResult() + client.get_evaluation_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_evaluation_result_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.GetEvaluationResultRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_evaluation_result), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.EvaluationResult() + ) + await client.get_evaluation_result(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_evaluation_result_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_evaluation_result), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.EvaluationResult() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_evaluation_result( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_evaluation_result_flattened_error(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_evaluation_result( + evaluation_service.GetEvaluationResultRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_evaluation_result_flattened_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_evaluation_result), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.EvaluationResult() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.EvaluationResult() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_evaluation_result( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_evaluation_result_flattened_error_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_evaluation_result( + evaluation_service.GetEvaluationResultRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.GetEvaluationDatasetRequest, + dict, + ], +) +def test_get_evaluation_dataset(request_type, transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_evaluation_dataset), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.EvaluationDataset( + name="name_value", + display_name="display_name_value", + evaluations=["evaluations_value"], + etag="etag_value", + created_by="created_by_value", + last_updated_by="last_updated_by_value", + ) + response = client.get_evaluation_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = evaluation_service.GetEvaluationDatasetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.EvaluationDataset) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.evaluations == ["evaluations_value"] + assert response.etag == "etag_value" + assert response.created_by == "created_by_value" + assert response.last_updated_by == "last_updated_by_value" + + +def test_get_evaluation_dataset_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = evaluation_service.GetEvaluationDatasetRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_evaluation_dataset), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_evaluation_dataset(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.GetEvaluationDatasetRequest( + name="name_value", + ) + + +def test_get_evaluation_dataset_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_evaluation_dataset + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_evaluation_dataset] = ( + mock_rpc + ) + request = {} + client.get_evaluation_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_evaluation_dataset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_evaluation_dataset_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_evaluation_dataset + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_evaluation_dataset + ] = mock_rpc + + request = {} + await client.get_evaluation_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_evaluation_dataset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_evaluation_dataset_async( + transport: str = "grpc_asyncio", + request_type=evaluation_service.GetEvaluationDatasetRequest, +): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_evaluation_dataset), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.EvaluationDataset( + name="name_value", + display_name="display_name_value", + evaluations=["evaluations_value"], + etag="etag_value", + created_by="created_by_value", + last_updated_by="last_updated_by_value", + ) + ) + response = await client.get_evaluation_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = evaluation_service.GetEvaluationDatasetRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.EvaluationDataset) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.evaluations == ["evaluations_value"] + assert response.etag == "etag_value" + assert response.created_by == "created_by_value" + assert response.last_updated_by == "last_updated_by_value" + + +@pytest.mark.asyncio +async def test_get_evaluation_dataset_async_from_dict(): + await test_get_evaluation_dataset_async(request_type=dict) + + +def test_get_evaluation_dataset_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.GetEvaluationDatasetRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_evaluation_dataset), "__call__" + ) as call: + call.return_value = evaluation.EvaluationDataset() + client.get_evaluation_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_evaluation_dataset_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.GetEvaluationDatasetRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_evaluation_dataset), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.EvaluationDataset() + ) + await client.get_evaluation_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_evaluation_dataset_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_evaluation_dataset), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.EvaluationDataset() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_evaluation_dataset( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_evaluation_dataset_flattened_error(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_evaluation_dataset( + evaluation_service.GetEvaluationDatasetRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_evaluation_dataset_flattened_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_evaluation_dataset), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.EvaluationDataset() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.EvaluationDataset() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_evaluation_dataset( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_evaluation_dataset_flattened_error_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_evaluation_dataset( + evaluation_service.GetEvaluationDatasetRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.GetEvaluationRunRequest, + dict, + ], +) +def test_get_evaluation_run(request_type, transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_evaluation_run), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.EvaluationRun( + name="name_value", + display_name="display_name_value", + evaluation_results=["evaluation_results_value"], + initiated_by="initiated_by_value", + app_version="app_version_value", + app_version_display_name="app_version_display_name_value", + changelog="changelog_value", + evaluations=["evaluations_value"], + evaluation_dataset="evaluation_dataset_value", + evaluation_type=evaluation.EvaluationRun.EvaluationType.GOLDEN, + state=evaluation.EvaluationRun.EvaluationRunState.RUNNING, + run_count=989, + scheduled_evaluation_run="scheduled_evaluation_run_value", + golden_run_method=golden_run.GoldenRunMethod.STABLE, + ) + response = client.get_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = evaluation_service.GetEvaluationRunRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.EvaluationRun) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.evaluation_results == ["evaluation_results_value"] + assert response.initiated_by == "initiated_by_value" + assert response.app_version == "app_version_value" + assert response.app_version_display_name == "app_version_display_name_value" + assert response.changelog == "changelog_value" + assert response.evaluations == ["evaluations_value"] + assert response.evaluation_dataset == "evaluation_dataset_value" + assert response.evaluation_type == evaluation.EvaluationRun.EvaluationType.GOLDEN + assert response.state == evaluation.EvaluationRun.EvaluationRunState.RUNNING + assert response.run_count == 989 + assert response.scheduled_evaluation_run == "scheduled_evaluation_run_value" + assert response.golden_run_method == golden_run.GoldenRunMethod.STABLE + + +def test_get_evaluation_run_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = evaluation_service.GetEvaluationRunRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_evaluation_run), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_evaluation_run(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.GetEvaluationRunRequest( + name="name_value", + ) + + +def test_get_evaluation_run_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_evaluation_run in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_evaluation_run] = ( + mock_rpc + ) + request = {} + client.get_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_evaluation_run(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_evaluation_run_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_evaluation_run + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_evaluation_run + ] = mock_rpc + + request = {} + await client.get_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_evaluation_run(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_evaluation_run_async( + transport: str = "grpc_asyncio", + request_type=evaluation_service.GetEvaluationRunRequest, +): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_evaluation_run), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.EvaluationRun( + name="name_value", + display_name="display_name_value", + evaluation_results=["evaluation_results_value"], + initiated_by="initiated_by_value", + app_version="app_version_value", + app_version_display_name="app_version_display_name_value", + changelog="changelog_value", + evaluations=["evaluations_value"], + evaluation_dataset="evaluation_dataset_value", + evaluation_type=evaluation.EvaluationRun.EvaluationType.GOLDEN, + state=evaluation.EvaluationRun.EvaluationRunState.RUNNING, + run_count=989, + scheduled_evaluation_run="scheduled_evaluation_run_value", + golden_run_method=golden_run.GoldenRunMethod.STABLE, + ) + ) + response = await client.get_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = evaluation_service.GetEvaluationRunRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.EvaluationRun) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.evaluation_results == ["evaluation_results_value"] + assert response.initiated_by == "initiated_by_value" + assert response.app_version == "app_version_value" + assert response.app_version_display_name == "app_version_display_name_value" + assert response.changelog == "changelog_value" + assert response.evaluations == ["evaluations_value"] + assert response.evaluation_dataset == "evaluation_dataset_value" + assert response.evaluation_type == evaluation.EvaluationRun.EvaluationType.GOLDEN + assert response.state == evaluation.EvaluationRun.EvaluationRunState.RUNNING + assert response.run_count == 989 + assert response.scheduled_evaluation_run == "scheduled_evaluation_run_value" + assert response.golden_run_method == golden_run.GoldenRunMethod.STABLE + + +@pytest.mark.asyncio +async def test_get_evaluation_run_async_from_dict(): + await test_get_evaluation_run_async(request_type=dict) + + +def test_get_evaluation_run_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.GetEvaluationRunRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_evaluation_run), "__call__" + ) as call: + call.return_value = evaluation.EvaluationRun() + client.get_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_evaluation_run_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.GetEvaluationRunRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_evaluation_run), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.EvaluationRun() + ) + await client.get_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_evaluation_run_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_evaluation_run), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.EvaluationRun() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_evaluation_run( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_evaluation_run_flattened_error(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_evaluation_run( + evaluation_service.GetEvaluationRunRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_evaluation_run_flattened_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_evaluation_run), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.EvaluationRun() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.EvaluationRun() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_evaluation_run( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_evaluation_run_flattened_error_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_evaluation_run( + evaluation_service.GetEvaluationRunRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.ListEvaluationsRequest, + dict, + ], +) +def test_list_evaluations(request_type, transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_evaluations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_service.ListEvaluationsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_evaluations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = evaluation_service.ListEvaluationsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEvaluationsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_evaluations_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = evaluation_service.ListEvaluationsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + evaluation_filter="evaluation_filter_value", + evaluation_run_filter="evaluation_run_filter_value", + order_by="order_by_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_evaluations), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_evaluations(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.ListEvaluationsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + evaluation_filter="evaluation_filter_value", + evaluation_run_filter="evaluation_run_filter_value", + order_by="order_by_value", + ) + + +def test_list_evaluations_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_evaluations in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_evaluations] = ( + mock_rpc + ) + request = {} + client.list_evaluations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_evaluations(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_evaluations_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_evaluations + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_evaluations + ] = mock_rpc + + request = {} + await client.list_evaluations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_evaluations(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_evaluations_async( + transport: str = "grpc_asyncio", + request_type=evaluation_service.ListEvaluationsRequest, +): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_evaluations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.ListEvaluationsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_evaluations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = evaluation_service.ListEvaluationsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEvaluationsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_evaluations_async_from_dict(): + await test_list_evaluations_async(request_type=dict) + + +def test_list_evaluations_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.ListEvaluationsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_evaluations), "__call__") as call: + call.return_value = evaluation_service.ListEvaluationsResponse() + client.list_evaluations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_evaluations_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.ListEvaluationsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_evaluations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.ListEvaluationsResponse() + ) + await client.list_evaluations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_evaluations_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_evaluations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_service.ListEvaluationsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_evaluations( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_evaluations_flattened_error(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_evaluations( + evaluation_service.ListEvaluationsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_evaluations_flattened_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_evaluations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_service.ListEvaluationsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.ListEvaluationsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_evaluations( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_evaluations_flattened_error_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_evaluations( + evaluation_service.ListEvaluationsRequest(), + parent="parent_value", + ) + + +def test_list_evaluations_pager(transport_name: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_evaluations), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_evaluations(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, evaluation.Evaluation) for i in results) + + +def test_list_evaluations_pages(transport_name: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_evaluations), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + ), + RuntimeError, + ) + pages = list(client.list_evaluations(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_evaluations_async_pager(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluations), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_evaluations( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, evaluation.Evaluation) for i in responses) + + +@pytest.mark.asyncio +async def test_list_evaluations_async_pages(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluations), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_evaluations(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.ListEvaluationResultsRequest, + dict, + ], +) +def test_list_evaluation_results(request_type, transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_results), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_service.ListEvaluationResultsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_evaluation_results(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = evaluation_service.ListEvaluationResultsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEvaluationResultsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_evaluation_results_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = evaluation_service.ListEvaluationResultsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_results), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_evaluation_results(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.ListEvaluationResultsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + +def test_list_evaluation_results_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_evaluation_results + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_evaluation_results + ] = mock_rpc + request = {} + client.list_evaluation_results(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_evaluation_results(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_evaluation_results_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_evaluation_results + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_evaluation_results + ] = mock_rpc + + request = {} + await client.list_evaluation_results(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_evaluation_results(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_evaluation_results_async( + transport: str = "grpc_asyncio", + request_type=evaluation_service.ListEvaluationResultsRequest, +): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_results), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.ListEvaluationResultsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_evaluation_results(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = evaluation_service.ListEvaluationResultsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEvaluationResultsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_evaluation_results_async_from_dict(): + await test_list_evaluation_results_async(request_type=dict) + + +def test_list_evaluation_results_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.ListEvaluationResultsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_results), "__call__" + ) as call: + call.return_value = evaluation_service.ListEvaluationResultsResponse() + client.list_evaluation_results(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_evaluation_results_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.ListEvaluationResultsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_results), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.ListEvaluationResultsResponse() + ) + await client.list_evaluation_results(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_evaluation_results_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_results), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_service.ListEvaluationResultsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_evaluation_results( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_evaluation_results_flattened_error(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_evaluation_results( + evaluation_service.ListEvaluationResultsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_evaluation_results_flattened_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_results), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_service.ListEvaluationResultsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.ListEvaluationResultsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_evaluation_results( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_evaluation_results_flattened_error_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_evaluation_results( + evaluation_service.ListEvaluationResultsRequest(), + parent="parent_value", + ) + + +def test_list_evaluation_results_pager(transport_name: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_results), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation.EvaluationResult(), + evaluation.EvaluationResult(), + evaluation.EvaluationResult(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation.EvaluationResult(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation.EvaluationResult(), + evaluation.EvaluationResult(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_evaluation_results(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, evaluation.EvaluationResult) for i in results) + + +def test_list_evaluation_results_pages(transport_name: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_results), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation.EvaluationResult(), + evaluation.EvaluationResult(), + evaluation.EvaluationResult(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation.EvaluationResult(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation.EvaluationResult(), + evaluation.EvaluationResult(), + ], + ), + RuntimeError, + ) + pages = list(client.list_evaluation_results(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_evaluation_results_async_pager(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_results), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation.EvaluationResult(), + evaluation.EvaluationResult(), + evaluation.EvaluationResult(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation.EvaluationResult(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation.EvaluationResult(), + evaluation.EvaluationResult(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_evaluation_results( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, evaluation.EvaluationResult) for i in responses) + + +@pytest.mark.asyncio +async def test_list_evaluation_results_async_pages(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_results), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation.EvaluationResult(), + evaluation.EvaluationResult(), + evaluation.EvaluationResult(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation.EvaluationResult(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation.EvaluationResult(), + evaluation.EvaluationResult(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_evaluation_results(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.ListEvaluationDatasetsRequest, + dict, + ], +) +def test_list_evaluation_datasets(request_type, transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_datasets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_service.ListEvaluationDatasetsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_evaluation_datasets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = evaluation_service.ListEvaluationDatasetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEvaluationDatasetsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_evaluation_datasets_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = evaluation_service.ListEvaluationDatasetsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_datasets), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_evaluation_datasets(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.ListEvaluationDatasetsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + +def test_list_evaluation_datasets_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_evaluation_datasets + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_evaluation_datasets + ] = mock_rpc + request = {} + client.list_evaluation_datasets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_evaluation_datasets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_evaluation_datasets_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_evaluation_datasets + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_evaluation_datasets + ] = mock_rpc + + request = {} + await client.list_evaluation_datasets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_evaluation_datasets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_evaluation_datasets_async( + transport: str = "grpc_asyncio", + request_type=evaluation_service.ListEvaluationDatasetsRequest, +): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_datasets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.ListEvaluationDatasetsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_evaluation_datasets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = evaluation_service.ListEvaluationDatasetsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEvaluationDatasetsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_evaluation_datasets_async_from_dict(): + await test_list_evaluation_datasets_async(request_type=dict) + + +def test_list_evaluation_datasets_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.ListEvaluationDatasetsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_datasets), "__call__" + ) as call: + call.return_value = evaluation_service.ListEvaluationDatasetsResponse() + client.list_evaluation_datasets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_evaluation_datasets_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.ListEvaluationDatasetsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_datasets), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.ListEvaluationDatasetsResponse() + ) + await client.list_evaluation_datasets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_evaluation_datasets_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_datasets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_service.ListEvaluationDatasetsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_evaluation_datasets( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_evaluation_datasets_flattened_error(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_evaluation_datasets( + evaluation_service.ListEvaluationDatasetsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_evaluation_datasets_flattened_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_datasets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_service.ListEvaluationDatasetsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.ListEvaluationDatasetsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_evaluation_datasets( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_evaluation_datasets_flattened_error_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_evaluation_datasets( + evaluation_service.ListEvaluationDatasetsRequest(), + parent="parent_value", + ) + + +def test_list_evaluation_datasets_pager(transport_name: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_datasets), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + evaluation_service.ListEvaluationDatasetsResponse( + evaluation_datasets=[ + evaluation.EvaluationDataset(), + evaluation.EvaluationDataset(), + evaluation.EvaluationDataset(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationDatasetsResponse( + evaluation_datasets=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationDatasetsResponse( + evaluation_datasets=[ + evaluation.EvaluationDataset(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationDatasetsResponse( + evaluation_datasets=[ + evaluation.EvaluationDataset(), + evaluation.EvaluationDataset(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_evaluation_datasets( + request={}, retry=retry, timeout=timeout + ) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, evaluation.EvaluationDataset) for i in results) + + +def test_list_evaluation_datasets_pages(transport_name: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_datasets), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + evaluation_service.ListEvaluationDatasetsResponse( + evaluation_datasets=[ + evaluation.EvaluationDataset(), + evaluation.EvaluationDataset(), + evaluation.EvaluationDataset(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationDatasetsResponse( + evaluation_datasets=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationDatasetsResponse( + evaluation_datasets=[ + evaluation.EvaluationDataset(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationDatasetsResponse( + evaluation_datasets=[ + evaluation.EvaluationDataset(), + evaluation.EvaluationDataset(), + ], + ), + RuntimeError, + ) + pages = list(client.list_evaluation_datasets(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_evaluation_datasets_async_pager(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_datasets), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + evaluation_service.ListEvaluationDatasetsResponse( + evaluation_datasets=[ + evaluation.EvaluationDataset(), + evaluation.EvaluationDataset(), + evaluation.EvaluationDataset(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationDatasetsResponse( + evaluation_datasets=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationDatasetsResponse( + evaluation_datasets=[ + evaluation.EvaluationDataset(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationDatasetsResponse( + evaluation_datasets=[ + evaluation.EvaluationDataset(), + evaluation.EvaluationDataset(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_evaluation_datasets( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, evaluation.EvaluationDataset) for i in responses) + + +@pytest.mark.asyncio +async def test_list_evaluation_datasets_async_pages(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_datasets), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + evaluation_service.ListEvaluationDatasetsResponse( + evaluation_datasets=[ + evaluation.EvaluationDataset(), + evaluation.EvaluationDataset(), + evaluation.EvaluationDataset(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationDatasetsResponse( + evaluation_datasets=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationDatasetsResponse( + evaluation_datasets=[ + evaluation.EvaluationDataset(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationDatasetsResponse( + evaluation_datasets=[ + evaluation.EvaluationDataset(), + evaluation.EvaluationDataset(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_evaluation_datasets(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.ListEvaluationRunsRequest, + dict, + ], +) +def test_list_evaluation_runs(request_type, transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_runs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_service.ListEvaluationRunsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_evaluation_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = evaluation_service.ListEvaluationRunsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEvaluationRunsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_evaluation_runs_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = evaluation_service.ListEvaluationRunsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_runs), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_evaluation_runs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.ListEvaluationRunsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + +def test_list_evaluation_runs_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_evaluation_runs in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_evaluation_runs] = ( + mock_rpc + ) + request = {} + client.list_evaluation_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_evaluation_runs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_evaluation_runs_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_evaluation_runs + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_evaluation_runs + ] = mock_rpc + + request = {} + await client.list_evaluation_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_evaluation_runs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_evaluation_runs_async( + transport: str = "grpc_asyncio", + request_type=evaluation_service.ListEvaluationRunsRequest, +): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_runs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.ListEvaluationRunsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_evaluation_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = evaluation_service.ListEvaluationRunsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEvaluationRunsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_evaluation_runs_async_from_dict(): + await test_list_evaluation_runs_async(request_type=dict) + + +def test_list_evaluation_runs_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.ListEvaluationRunsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_runs), "__call__" + ) as call: + call.return_value = evaluation_service.ListEvaluationRunsResponse() + client.list_evaluation_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_evaluation_runs_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.ListEvaluationRunsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_runs), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.ListEvaluationRunsResponse() + ) + await client.list_evaluation_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_evaluation_runs_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_runs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_service.ListEvaluationRunsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_evaluation_runs( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_evaluation_runs_flattened_error(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_evaluation_runs( + evaluation_service.ListEvaluationRunsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_evaluation_runs_flattened_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_runs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_service.ListEvaluationRunsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.ListEvaluationRunsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_evaluation_runs( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_evaluation_runs_flattened_error_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_evaluation_runs( + evaluation_service.ListEvaluationRunsRequest(), + parent="parent_value", + ) + + +def test_list_evaluation_runs_pager(transport_name: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_runs), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + evaluation_service.ListEvaluationRunsResponse( + evaluation_runs=[ + evaluation.EvaluationRun(), + evaluation.EvaluationRun(), + evaluation.EvaluationRun(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationRunsResponse( + evaluation_runs=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationRunsResponse( + evaluation_runs=[ + evaluation.EvaluationRun(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationRunsResponse( + evaluation_runs=[ + evaluation.EvaluationRun(), + evaluation.EvaluationRun(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_evaluation_runs(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, evaluation.EvaluationRun) for i in results) + + +def test_list_evaluation_runs_pages(transport_name: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_runs), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + evaluation_service.ListEvaluationRunsResponse( + evaluation_runs=[ + evaluation.EvaluationRun(), + evaluation.EvaluationRun(), + evaluation.EvaluationRun(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationRunsResponse( + evaluation_runs=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationRunsResponse( + evaluation_runs=[ + evaluation.EvaluationRun(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationRunsResponse( + evaluation_runs=[ + evaluation.EvaluationRun(), + evaluation.EvaluationRun(), + ], + ), + RuntimeError, + ) + pages = list(client.list_evaluation_runs(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_evaluation_runs_async_pager(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_runs), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + evaluation_service.ListEvaluationRunsResponse( + evaluation_runs=[ + evaluation.EvaluationRun(), + evaluation.EvaluationRun(), + evaluation.EvaluationRun(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationRunsResponse( + evaluation_runs=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationRunsResponse( + evaluation_runs=[ + evaluation.EvaluationRun(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationRunsResponse( + evaluation_runs=[ + evaluation.EvaluationRun(), + evaluation.EvaluationRun(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_evaluation_runs( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, evaluation.EvaluationRun) for i in responses) + + +@pytest.mark.asyncio +async def test_list_evaluation_runs_async_pages(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_runs), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + evaluation_service.ListEvaluationRunsResponse( + evaluation_runs=[ + evaluation.EvaluationRun(), + evaluation.EvaluationRun(), + evaluation.EvaluationRun(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationRunsResponse( + evaluation_runs=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationRunsResponse( + evaluation_runs=[ + evaluation.EvaluationRun(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationRunsResponse( + evaluation_runs=[ + evaluation.EvaluationRun(), + evaluation.EvaluationRun(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_evaluation_runs(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.ListEvaluationExpectationsRequest, + dict, + ], +) +def test_list_evaluation_expectations(request_type, transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_expectations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_service.ListEvaluationExpectationsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_evaluation_expectations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = evaluation_service.ListEvaluationExpectationsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEvaluationExpectationsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_evaluation_expectations_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = evaluation_service.ListEvaluationExpectationsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_expectations), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_evaluation_expectations(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.ListEvaluationExpectationsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + +def test_list_evaluation_expectations_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_evaluation_expectations + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_evaluation_expectations + ] = mock_rpc + request = {} + client.list_evaluation_expectations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_evaluation_expectations(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_evaluation_expectations_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_evaluation_expectations + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_evaluation_expectations + ] = mock_rpc + + request = {} + await client.list_evaluation_expectations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_evaluation_expectations(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_evaluation_expectations_async( + transport: str = "grpc_asyncio", + request_type=evaluation_service.ListEvaluationExpectationsRequest, +): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_expectations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.ListEvaluationExpectationsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_evaluation_expectations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = evaluation_service.ListEvaluationExpectationsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEvaluationExpectationsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_evaluation_expectations_async_from_dict(): + await test_list_evaluation_expectations_async(request_type=dict) + + +def test_list_evaluation_expectations_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.ListEvaluationExpectationsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_expectations), "__call__" + ) as call: + call.return_value = evaluation_service.ListEvaluationExpectationsResponse() + client.list_evaluation_expectations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_evaluation_expectations_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.ListEvaluationExpectationsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_expectations), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.ListEvaluationExpectationsResponse() + ) + await client.list_evaluation_expectations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_evaluation_expectations_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_expectations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_service.ListEvaluationExpectationsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_evaluation_expectations( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_evaluation_expectations_flattened_error(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_evaluation_expectations( + evaluation_service.ListEvaluationExpectationsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_evaluation_expectations_flattened_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_expectations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_service.ListEvaluationExpectationsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.ListEvaluationExpectationsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_evaluation_expectations( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_evaluation_expectations_flattened_error_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_evaluation_expectations( + evaluation_service.ListEvaluationExpectationsRequest(), + parent="parent_value", + ) + + +def test_list_evaluation_expectations_pager(transport_name: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_expectations), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + evaluation_service.ListEvaluationExpectationsResponse( + evaluation_expectations=[ + evaluation.EvaluationExpectation(), + evaluation.EvaluationExpectation(), + evaluation.EvaluationExpectation(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationExpectationsResponse( + evaluation_expectations=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationExpectationsResponse( + evaluation_expectations=[ + evaluation.EvaluationExpectation(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationExpectationsResponse( + evaluation_expectations=[ + evaluation.EvaluationExpectation(), + evaluation.EvaluationExpectation(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_evaluation_expectations( + request={}, retry=retry, timeout=timeout + ) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, evaluation.EvaluationExpectation) for i in results) + + +def test_list_evaluation_expectations_pages(transport_name: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_expectations), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + evaluation_service.ListEvaluationExpectationsResponse( + evaluation_expectations=[ + evaluation.EvaluationExpectation(), + evaluation.EvaluationExpectation(), + evaluation.EvaluationExpectation(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationExpectationsResponse( + evaluation_expectations=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationExpectationsResponse( + evaluation_expectations=[ + evaluation.EvaluationExpectation(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationExpectationsResponse( + evaluation_expectations=[ + evaluation.EvaluationExpectation(), + evaluation.EvaluationExpectation(), + ], + ), + RuntimeError, + ) + pages = list(client.list_evaluation_expectations(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_evaluation_expectations_async_pager(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_expectations), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + evaluation_service.ListEvaluationExpectationsResponse( + evaluation_expectations=[ + evaluation.EvaluationExpectation(), + evaluation.EvaluationExpectation(), + evaluation.EvaluationExpectation(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationExpectationsResponse( + evaluation_expectations=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationExpectationsResponse( + evaluation_expectations=[ + evaluation.EvaluationExpectation(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationExpectationsResponse( + evaluation_expectations=[ + evaluation.EvaluationExpectation(), + evaluation.EvaluationExpectation(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_evaluation_expectations( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, evaluation.EvaluationExpectation) for i in responses) + + +@pytest.mark.asyncio +async def test_list_evaluation_expectations_async_pages(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_expectations), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + evaluation_service.ListEvaluationExpectationsResponse( + evaluation_expectations=[ + evaluation.EvaluationExpectation(), + evaluation.EvaluationExpectation(), + evaluation.EvaluationExpectation(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationExpectationsResponse( + evaluation_expectations=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationExpectationsResponse( + evaluation_expectations=[ + evaluation.EvaluationExpectation(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationExpectationsResponse( + evaluation_expectations=[ + evaluation.EvaluationExpectation(), + evaluation.EvaluationExpectation(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_evaluation_expectations(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.GetEvaluationExpectationRequest, + dict, + ], +) +def test_get_evaluation_expectation(request_type, transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_evaluation_expectation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.EvaluationExpectation( + name="name_value", + display_name="display_name_value", + tags=["tags_value"], + etag="etag_value", + ) + response = client.get_evaluation_expectation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = evaluation_service.GetEvaluationExpectationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.EvaluationExpectation) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.tags == ["tags_value"] + assert response.etag == "etag_value" + + +def test_get_evaluation_expectation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = evaluation_service.GetEvaluationExpectationRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_evaluation_expectation), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_evaluation_expectation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.GetEvaluationExpectationRequest( + name="name_value", + ) + + +def test_get_evaluation_expectation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_evaluation_expectation + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_evaluation_expectation + ] = mock_rpc + request = {} + client.get_evaluation_expectation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_evaluation_expectation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_evaluation_expectation_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_evaluation_expectation + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_evaluation_expectation + ] = mock_rpc + + request = {} + await client.get_evaluation_expectation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_evaluation_expectation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_evaluation_expectation_async( + transport: str = "grpc_asyncio", + request_type=evaluation_service.GetEvaluationExpectationRequest, +): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_evaluation_expectation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.EvaluationExpectation( + name="name_value", + display_name="display_name_value", + tags=["tags_value"], + etag="etag_value", + ) + ) + response = await client.get_evaluation_expectation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = evaluation_service.GetEvaluationExpectationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.EvaluationExpectation) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.tags == ["tags_value"] + assert response.etag == "etag_value" + + +@pytest.mark.asyncio +async def test_get_evaluation_expectation_async_from_dict(): + await test_get_evaluation_expectation_async(request_type=dict) + + +def test_get_evaluation_expectation_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.GetEvaluationExpectationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_evaluation_expectation), "__call__" + ) as call: + call.return_value = evaluation.EvaluationExpectation() + client.get_evaluation_expectation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_evaluation_expectation_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.GetEvaluationExpectationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_evaluation_expectation), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.EvaluationExpectation() + ) + await client.get_evaluation_expectation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_evaluation_expectation_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_evaluation_expectation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.EvaluationExpectation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_evaluation_expectation( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_evaluation_expectation_flattened_error(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_evaluation_expectation( + evaluation_service.GetEvaluationExpectationRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_evaluation_expectation_flattened_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_evaluation_expectation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.EvaluationExpectation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.EvaluationExpectation() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_evaluation_expectation( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_evaluation_expectation_flattened_error_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_evaluation_expectation( + evaluation_service.GetEvaluationExpectationRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.CreateEvaluationExpectationRequest, + dict, + ], +) +def test_create_evaluation_expectation(request_type, transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation_expectation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.EvaluationExpectation( + name="name_value", + display_name="display_name_value", + tags=["tags_value"], + etag="etag_value", + ) + response = client.create_evaluation_expectation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = evaluation_service.CreateEvaluationExpectationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.EvaluationExpectation) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.tags == ["tags_value"] + assert response.etag == "etag_value" + + +def test_create_evaluation_expectation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = evaluation_service.CreateEvaluationExpectationRequest( + parent="parent_value", + evaluation_expectation_id="evaluation_expectation_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation_expectation), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_evaluation_expectation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.CreateEvaluationExpectationRequest( + parent="parent_value", + evaluation_expectation_id="evaluation_expectation_id_value", + ) + + +def test_create_evaluation_expectation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_evaluation_expectation + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_evaluation_expectation + ] = mock_rpc + request = {} + client.create_evaluation_expectation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_evaluation_expectation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_evaluation_expectation_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_evaluation_expectation + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_evaluation_expectation + ] = mock_rpc + + request = {} + await client.create_evaluation_expectation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_evaluation_expectation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_evaluation_expectation_async( + transport: str = "grpc_asyncio", + request_type=evaluation_service.CreateEvaluationExpectationRequest, +): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation_expectation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.EvaluationExpectation( + name="name_value", + display_name="display_name_value", + tags=["tags_value"], + etag="etag_value", + ) + ) + response = await client.create_evaluation_expectation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = evaluation_service.CreateEvaluationExpectationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.EvaluationExpectation) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.tags == ["tags_value"] + assert response.etag == "etag_value" + + +@pytest.mark.asyncio +async def test_create_evaluation_expectation_async_from_dict(): + await test_create_evaluation_expectation_async(request_type=dict) + + +def test_create_evaluation_expectation_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.CreateEvaluationExpectationRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation_expectation), "__call__" + ) as call: + call.return_value = evaluation.EvaluationExpectation() + client.create_evaluation_expectation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_evaluation_expectation_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.CreateEvaluationExpectationRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation_expectation), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.EvaluationExpectation() + ) + await client.create_evaluation_expectation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_evaluation_expectation_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation_expectation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.EvaluationExpectation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_evaluation_expectation( + parent="parent_value", + evaluation_expectation=evaluation.EvaluationExpectation( + llm_criteria=evaluation.EvaluationExpectation.LlmCriteria( + prompt="prompt_value" + ) + ), + evaluation_expectation_id="evaluation_expectation_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].evaluation_expectation + mock_val = evaluation.EvaluationExpectation( + llm_criteria=evaluation.EvaluationExpectation.LlmCriteria( + prompt="prompt_value" + ) + ) + assert arg == mock_val + arg = args[0].evaluation_expectation_id + mock_val = "evaluation_expectation_id_value" + assert arg == mock_val + + +def test_create_evaluation_expectation_flattened_error(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_evaluation_expectation( + evaluation_service.CreateEvaluationExpectationRequest(), + parent="parent_value", + evaluation_expectation=evaluation.EvaluationExpectation( + llm_criteria=evaluation.EvaluationExpectation.LlmCriteria( + prompt="prompt_value" + ) + ), + evaluation_expectation_id="evaluation_expectation_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_evaluation_expectation_flattened_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation_expectation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.EvaluationExpectation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.EvaluationExpectation() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_evaluation_expectation( + parent="parent_value", + evaluation_expectation=evaluation.EvaluationExpectation( + llm_criteria=evaluation.EvaluationExpectation.LlmCriteria( + prompt="prompt_value" + ) + ), + evaluation_expectation_id="evaluation_expectation_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].evaluation_expectation + mock_val = evaluation.EvaluationExpectation( + llm_criteria=evaluation.EvaluationExpectation.LlmCriteria( + prompt="prompt_value" + ) + ) + assert arg == mock_val + arg = args[0].evaluation_expectation_id + mock_val = "evaluation_expectation_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_evaluation_expectation_flattened_error_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_evaluation_expectation( + evaluation_service.CreateEvaluationExpectationRequest(), + parent="parent_value", + evaluation_expectation=evaluation.EvaluationExpectation( + llm_criteria=evaluation.EvaluationExpectation.LlmCriteria( + prompt="prompt_value" + ) + ), + evaluation_expectation_id="evaluation_expectation_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.UpdateEvaluationExpectationRequest, + dict, + ], +) +def test_update_evaluation_expectation(request_type, transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_evaluation_expectation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.EvaluationExpectation( + name="name_value", + display_name="display_name_value", + tags=["tags_value"], + etag="etag_value", + ) + response = client.update_evaluation_expectation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = evaluation_service.UpdateEvaluationExpectationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.EvaluationExpectation) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.tags == ["tags_value"] + assert response.etag == "etag_value" + + +def test_update_evaluation_expectation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = evaluation_service.UpdateEvaluationExpectationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_evaluation_expectation), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_evaluation_expectation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.UpdateEvaluationExpectationRequest() + + +def test_update_evaluation_expectation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_evaluation_expectation + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_evaluation_expectation + ] = mock_rpc + request = {} + client.update_evaluation_expectation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_evaluation_expectation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_evaluation_expectation_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_evaluation_expectation + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_evaluation_expectation + ] = mock_rpc + + request = {} + await client.update_evaluation_expectation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_evaluation_expectation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_evaluation_expectation_async( + transport: str = "grpc_asyncio", + request_type=evaluation_service.UpdateEvaluationExpectationRequest, +): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_evaluation_expectation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.EvaluationExpectation( + name="name_value", + display_name="display_name_value", + tags=["tags_value"], + etag="etag_value", + ) + ) + response = await client.update_evaluation_expectation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = evaluation_service.UpdateEvaluationExpectationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.EvaluationExpectation) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.tags == ["tags_value"] + assert response.etag == "etag_value" + + +@pytest.mark.asyncio +async def test_update_evaluation_expectation_async_from_dict(): + await test_update_evaluation_expectation_async(request_type=dict) + + +def test_update_evaluation_expectation_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.UpdateEvaluationExpectationRequest() + + request.evaluation_expectation.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_evaluation_expectation), "__call__" + ) as call: + call.return_value = evaluation.EvaluationExpectation() + client.update_evaluation_expectation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "evaluation_expectation.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_evaluation_expectation_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.UpdateEvaluationExpectationRequest() + + request.evaluation_expectation.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_evaluation_expectation), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.EvaluationExpectation() + ) + await client.update_evaluation_expectation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "evaluation_expectation.name=name_value", + ) in kw["metadata"] + + +def test_update_evaluation_expectation_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_evaluation_expectation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.EvaluationExpectation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_evaluation_expectation( + evaluation_expectation=evaluation.EvaluationExpectation( + llm_criteria=evaluation.EvaluationExpectation.LlmCriteria( + prompt="prompt_value" + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].evaluation_expectation + mock_val = evaluation.EvaluationExpectation( + llm_criteria=evaluation.EvaluationExpectation.LlmCriteria( + prompt="prompt_value" + ) + ) + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_evaluation_expectation_flattened_error(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_evaluation_expectation( + evaluation_service.UpdateEvaluationExpectationRequest(), + evaluation_expectation=evaluation.EvaluationExpectation( + llm_criteria=evaluation.EvaluationExpectation.LlmCriteria( + prompt="prompt_value" + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_evaluation_expectation_flattened_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_evaluation_expectation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.EvaluationExpectation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.EvaluationExpectation() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_evaluation_expectation( + evaluation_expectation=evaluation.EvaluationExpectation( + llm_criteria=evaluation.EvaluationExpectation.LlmCriteria( + prompt="prompt_value" + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].evaluation_expectation + mock_val = evaluation.EvaluationExpectation( + llm_criteria=evaluation.EvaluationExpectation.LlmCriteria( + prompt="prompt_value" + ) + ) + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_evaluation_expectation_flattened_error_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_evaluation_expectation( + evaluation_service.UpdateEvaluationExpectationRequest(), + evaluation_expectation=evaluation.EvaluationExpectation( + llm_criteria=evaluation.EvaluationExpectation.LlmCriteria( + prompt="prompt_value" + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.DeleteEvaluationExpectationRequest, + dict, + ], +) +def test_delete_evaluation_expectation(request_type, transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_expectation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_evaluation_expectation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = evaluation_service.DeleteEvaluationExpectationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_evaluation_expectation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = evaluation_service.DeleteEvaluationExpectationRequest( + name="name_value", + etag="etag_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_expectation), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_evaluation_expectation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.DeleteEvaluationExpectationRequest( + name="name_value", + etag="etag_value", + ) + + +def test_delete_evaluation_expectation_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_evaluation_expectation + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_evaluation_expectation + ] = mock_rpc + request = {} + client.delete_evaluation_expectation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_evaluation_expectation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_evaluation_expectation_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_evaluation_expectation + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_evaluation_expectation + ] = mock_rpc + + request = {} + await client.delete_evaluation_expectation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_evaluation_expectation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_evaluation_expectation_async( + transport: str = "grpc_asyncio", + request_type=evaluation_service.DeleteEvaluationExpectationRequest, +): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_expectation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_evaluation_expectation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = evaluation_service.DeleteEvaluationExpectationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_evaluation_expectation_async_from_dict(): + await test_delete_evaluation_expectation_async(request_type=dict) + + +def test_delete_evaluation_expectation_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.DeleteEvaluationExpectationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_expectation), "__call__" + ) as call: + call.return_value = None + client.delete_evaluation_expectation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_evaluation_expectation_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.DeleteEvaluationExpectationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_expectation), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_evaluation_expectation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_evaluation_expectation_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_expectation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_evaluation_expectation( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_evaluation_expectation_flattened_error(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_evaluation_expectation( + evaluation_service.DeleteEvaluationExpectationRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_evaluation_expectation_flattened_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_expectation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_evaluation_expectation( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_evaluation_expectation_flattened_error_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_evaluation_expectation( + evaluation_service.DeleteEvaluationExpectationRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.CreateScheduledEvaluationRunRequest, + dict, + ], +) +def test_create_scheduled_evaluation_run(request_type, transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scheduled_evaluation_run), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.ScheduledEvaluationRun( + name="name_value", + display_name="display_name_value", + description="description_value", + active=True, + last_completed_run="last_completed_run_value", + total_executions=1738, + created_by="created_by_value", + last_updated_by="last_updated_by_value", + etag="etag_value", + ) + response = client.create_scheduled_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = evaluation_service.CreateScheduledEvaluationRunRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.ScheduledEvaluationRun) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.active is True + assert response.last_completed_run == "last_completed_run_value" + assert response.total_executions == 1738 + assert response.created_by == "created_by_value" + assert response.last_updated_by == "last_updated_by_value" + assert response.etag == "etag_value" + + +def test_create_scheduled_evaluation_run_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = evaluation_service.CreateScheduledEvaluationRunRequest( + parent="parent_value", + scheduled_evaluation_run_id="scheduled_evaluation_run_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scheduled_evaluation_run), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_scheduled_evaluation_run(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.CreateScheduledEvaluationRunRequest( + parent="parent_value", + scheduled_evaluation_run_id="scheduled_evaluation_run_id_value", + ) + + +def test_create_scheduled_evaluation_run_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_scheduled_evaluation_run + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_scheduled_evaluation_run + ] = mock_rpc + request = {} + client.create_scheduled_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_scheduled_evaluation_run(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_scheduled_evaluation_run_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_scheduled_evaluation_run + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_scheduled_evaluation_run + ] = mock_rpc + + request = {} + await client.create_scheduled_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_scheduled_evaluation_run(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_scheduled_evaluation_run_async( + transport: str = "grpc_asyncio", + request_type=evaluation_service.CreateScheduledEvaluationRunRequest, +): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scheduled_evaluation_run), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.ScheduledEvaluationRun( + name="name_value", + display_name="display_name_value", + description="description_value", + active=True, + last_completed_run="last_completed_run_value", + total_executions=1738, + created_by="created_by_value", + last_updated_by="last_updated_by_value", + etag="etag_value", + ) + ) + response = await client.create_scheduled_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = evaluation_service.CreateScheduledEvaluationRunRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.ScheduledEvaluationRun) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.active is True + assert response.last_completed_run == "last_completed_run_value" + assert response.total_executions == 1738 + assert response.created_by == "created_by_value" + assert response.last_updated_by == "last_updated_by_value" + assert response.etag == "etag_value" + + +@pytest.mark.asyncio +async def test_create_scheduled_evaluation_run_async_from_dict(): + await test_create_scheduled_evaluation_run_async(request_type=dict) + + +def test_create_scheduled_evaluation_run_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.CreateScheduledEvaluationRunRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scheduled_evaluation_run), "__call__" + ) as call: + call.return_value = evaluation.ScheduledEvaluationRun() + client.create_scheduled_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_scheduled_evaluation_run_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.CreateScheduledEvaluationRunRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scheduled_evaluation_run), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.ScheduledEvaluationRun() + ) + await client.create_scheduled_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_scheduled_evaluation_run_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scheduled_evaluation_run), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.ScheduledEvaluationRun() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_scheduled_evaluation_run( + parent="parent_value", + scheduled_evaluation_run=evaluation.ScheduledEvaluationRun( + name="name_value" + ), + scheduled_evaluation_run_id="scheduled_evaluation_run_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].scheduled_evaluation_run + mock_val = evaluation.ScheduledEvaluationRun(name="name_value") + assert arg == mock_val + arg = args[0].scheduled_evaluation_run_id + mock_val = "scheduled_evaluation_run_id_value" + assert arg == mock_val + + +def test_create_scheduled_evaluation_run_flattened_error(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_scheduled_evaluation_run( + evaluation_service.CreateScheduledEvaluationRunRequest(), + parent="parent_value", + scheduled_evaluation_run=evaluation.ScheduledEvaluationRun( + name="name_value" + ), + scheduled_evaluation_run_id="scheduled_evaluation_run_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_scheduled_evaluation_run_flattened_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_scheduled_evaluation_run), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.ScheduledEvaluationRun() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.ScheduledEvaluationRun() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_scheduled_evaluation_run( + parent="parent_value", + scheduled_evaluation_run=evaluation.ScheduledEvaluationRun( + name="name_value" + ), + scheduled_evaluation_run_id="scheduled_evaluation_run_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].scheduled_evaluation_run + mock_val = evaluation.ScheduledEvaluationRun(name="name_value") + assert arg == mock_val + arg = args[0].scheduled_evaluation_run_id + mock_val = "scheduled_evaluation_run_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_scheduled_evaluation_run_flattened_error_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_scheduled_evaluation_run( + evaluation_service.CreateScheduledEvaluationRunRequest(), + parent="parent_value", + scheduled_evaluation_run=evaluation.ScheduledEvaluationRun( + name="name_value" + ), + scheduled_evaluation_run_id="scheduled_evaluation_run_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.GetScheduledEvaluationRunRequest, + dict, + ], +) +def test_get_scheduled_evaluation_run(request_type, transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scheduled_evaluation_run), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.ScheduledEvaluationRun( + name="name_value", + display_name="display_name_value", + description="description_value", + active=True, + last_completed_run="last_completed_run_value", + total_executions=1738, + created_by="created_by_value", + last_updated_by="last_updated_by_value", + etag="etag_value", + ) + response = client.get_scheduled_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = evaluation_service.GetScheduledEvaluationRunRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.ScheduledEvaluationRun) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.active is True + assert response.last_completed_run == "last_completed_run_value" + assert response.total_executions == 1738 + assert response.created_by == "created_by_value" + assert response.last_updated_by == "last_updated_by_value" + assert response.etag == "etag_value" + + +def test_get_scheduled_evaluation_run_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = evaluation_service.GetScheduledEvaluationRunRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scheduled_evaluation_run), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_scheduled_evaluation_run(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.GetScheduledEvaluationRunRequest( + name="name_value", + ) + + +def test_get_scheduled_evaluation_run_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_scheduled_evaluation_run + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_scheduled_evaluation_run + ] = mock_rpc + request = {} + client.get_scheduled_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_scheduled_evaluation_run(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_scheduled_evaluation_run_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_scheduled_evaluation_run + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_scheduled_evaluation_run + ] = mock_rpc + + request = {} + await client.get_scheduled_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_scheduled_evaluation_run(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_scheduled_evaluation_run_async( + transport: str = "grpc_asyncio", + request_type=evaluation_service.GetScheduledEvaluationRunRequest, +): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scheduled_evaluation_run), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.ScheduledEvaluationRun( + name="name_value", + display_name="display_name_value", + description="description_value", + active=True, + last_completed_run="last_completed_run_value", + total_executions=1738, + created_by="created_by_value", + last_updated_by="last_updated_by_value", + etag="etag_value", + ) + ) + response = await client.get_scheduled_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = evaluation_service.GetScheduledEvaluationRunRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.ScheduledEvaluationRun) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.active is True + assert response.last_completed_run == "last_completed_run_value" + assert response.total_executions == 1738 + assert response.created_by == "created_by_value" + assert response.last_updated_by == "last_updated_by_value" + assert response.etag == "etag_value" + + +@pytest.mark.asyncio +async def test_get_scheduled_evaluation_run_async_from_dict(): + await test_get_scheduled_evaluation_run_async(request_type=dict) + + +def test_get_scheduled_evaluation_run_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.GetScheduledEvaluationRunRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scheduled_evaluation_run), "__call__" + ) as call: + call.return_value = evaluation.ScheduledEvaluationRun() + client.get_scheduled_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_scheduled_evaluation_run_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.GetScheduledEvaluationRunRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scheduled_evaluation_run), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.ScheduledEvaluationRun() + ) + await client.get_scheduled_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_scheduled_evaluation_run_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scheduled_evaluation_run), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.ScheduledEvaluationRun() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_scheduled_evaluation_run( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_scheduled_evaluation_run_flattened_error(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_scheduled_evaluation_run( + evaluation_service.GetScheduledEvaluationRunRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_scheduled_evaluation_run_flattened_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_scheduled_evaluation_run), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.ScheduledEvaluationRun() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.ScheduledEvaluationRun() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_scheduled_evaluation_run( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_scheduled_evaluation_run_flattened_error_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_scheduled_evaluation_run( + evaluation_service.GetScheduledEvaluationRunRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.ListScheduledEvaluationRunsRequest, + dict, + ], +) +def test_list_scheduled_evaluation_runs(request_type, transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scheduled_evaluation_runs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_service.ListScheduledEvaluationRunsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_scheduled_evaluation_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = evaluation_service.ListScheduledEvaluationRunsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScheduledEvaluationRunsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_scheduled_evaluation_runs_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = evaluation_service.ListScheduledEvaluationRunsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scheduled_evaluation_runs), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_scheduled_evaluation_runs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.ListScheduledEvaluationRunsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + +def test_list_scheduled_evaluation_runs_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_scheduled_evaluation_runs + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_scheduled_evaluation_runs + ] = mock_rpc + request = {} + client.list_scheduled_evaluation_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_scheduled_evaluation_runs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_scheduled_evaluation_runs_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_scheduled_evaluation_runs + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_scheduled_evaluation_runs + ] = mock_rpc + + request = {} + await client.list_scheduled_evaluation_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_scheduled_evaluation_runs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_scheduled_evaluation_runs_async( + transport: str = "grpc_asyncio", + request_type=evaluation_service.ListScheduledEvaluationRunsRequest, +): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scheduled_evaluation_runs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.ListScheduledEvaluationRunsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_scheduled_evaluation_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = evaluation_service.ListScheduledEvaluationRunsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScheduledEvaluationRunsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_scheduled_evaluation_runs_async_from_dict(): + await test_list_scheduled_evaluation_runs_async(request_type=dict) + + +def test_list_scheduled_evaluation_runs_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.ListScheduledEvaluationRunsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scheduled_evaluation_runs), "__call__" + ) as call: + call.return_value = evaluation_service.ListScheduledEvaluationRunsResponse() + client.list_scheduled_evaluation_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_scheduled_evaluation_runs_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.ListScheduledEvaluationRunsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scheduled_evaluation_runs), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.ListScheduledEvaluationRunsResponse() + ) + await client.list_scheduled_evaluation_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_scheduled_evaluation_runs_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scheduled_evaluation_runs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_service.ListScheduledEvaluationRunsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_scheduled_evaluation_runs( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_scheduled_evaluation_runs_flattened_error(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_scheduled_evaluation_runs( + evaluation_service.ListScheduledEvaluationRunsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_scheduled_evaluation_runs_flattened_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scheduled_evaluation_runs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_service.ListScheduledEvaluationRunsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.ListScheduledEvaluationRunsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_scheduled_evaluation_runs( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_scheduled_evaluation_runs_flattened_error_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_scheduled_evaluation_runs( + evaluation_service.ListScheduledEvaluationRunsRequest(), + parent="parent_value", + ) + + +def test_list_scheduled_evaluation_runs_pager(transport_name: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scheduled_evaluation_runs), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + evaluation_service.ListScheduledEvaluationRunsResponse( + scheduled_evaluation_runs=[ + evaluation.ScheduledEvaluationRun(), + evaluation.ScheduledEvaluationRun(), + evaluation.ScheduledEvaluationRun(), + ], + next_page_token="abc", + ), + evaluation_service.ListScheduledEvaluationRunsResponse( + scheduled_evaluation_runs=[], + next_page_token="def", + ), + evaluation_service.ListScheduledEvaluationRunsResponse( + scheduled_evaluation_runs=[ + evaluation.ScheduledEvaluationRun(), + ], + next_page_token="ghi", + ), + evaluation_service.ListScheduledEvaluationRunsResponse( + scheduled_evaluation_runs=[ + evaluation.ScheduledEvaluationRun(), + evaluation.ScheduledEvaluationRun(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_scheduled_evaluation_runs( + request={}, retry=retry, timeout=timeout + ) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, evaluation.ScheduledEvaluationRun) for i in results) + + +def test_list_scheduled_evaluation_runs_pages(transport_name: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scheduled_evaluation_runs), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + evaluation_service.ListScheduledEvaluationRunsResponse( + scheduled_evaluation_runs=[ + evaluation.ScheduledEvaluationRun(), + evaluation.ScheduledEvaluationRun(), + evaluation.ScheduledEvaluationRun(), + ], + next_page_token="abc", + ), + evaluation_service.ListScheduledEvaluationRunsResponse( + scheduled_evaluation_runs=[], + next_page_token="def", + ), + evaluation_service.ListScheduledEvaluationRunsResponse( + scheduled_evaluation_runs=[ + evaluation.ScheduledEvaluationRun(), + ], + next_page_token="ghi", + ), + evaluation_service.ListScheduledEvaluationRunsResponse( + scheduled_evaluation_runs=[ + evaluation.ScheduledEvaluationRun(), + evaluation.ScheduledEvaluationRun(), + ], + ), + RuntimeError, + ) + pages = list(client.list_scheduled_evaluation_runs(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_scheduled_evaluation_runs_async_pager(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scheduled_evaluation_runs), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + evaluation_service.ListScheduledEvaluationRunsResponse( + scheduled_evaluation_runs=[ + evaluation.ScheduledEvaluationRun(), + evaluation.ScheduledEvaluationRun(), + evaluation.ScheduledEvaluationRun(), + ], + next_page_token="abc", + ), + evaluation_service.ListScheduledEvaluationRunsResponse( + scheduled_evaluation_runs=[], + next_page_token="def", + ), + evaluation_service.ListScheduledEvaluationRunsResponse( + scheduled_evaluation_runs=[ + evaluation.ScheduledEvaluationRun(), + ], + next_page_token="ghi", + ), + evaluation_service.ListScheduledEvaluationRunsResponse( + scheduled_evaluation_runs=[ + evaluation.ScheduledEvaluationRun(), + evaluation.ScheduledEvaluationRun(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_scheduled_evaluation_runs( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, evaluation.ScheduledEvaluationRun) for i in responses) + + +@pytest.mark.asyncio +async def test_list_scheduled_evaluation_runs_async_pages(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_scheduled_evaluation_runs), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + evaluation_service.ListScheduledEvaluationRunsResponse( + scheduled_evaluation_runs=[ + evaluation.ScheduledEvaluationRun(), + evaluation.ScheduledEvaluationRun(), + evaluation.ScheduledEvaluationRun(), + ], + next_page_token="abc", + ), + evaluation_service.ListScheduledEvaluationRunsResponse( + scheduled_evaluation_runs=[], + next_page_token="def", + ), + evaluation_service.ListScheduledEvaluationRunsResponse( + scheduled_evaluation_runs=[ + evaluation.ScheduledEvaluationRun(), + ], + next_page_token="ghi", + ), + evaluation_service.ListScheduledEvaluationRunsResponse( + scheduled_evaluation_runs=[ + evaluation.ScheduledEvaluationRun(), + evaluation.ScheduledEvaluationRun(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_scheduled_evaluation_runs(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.UpdateScheduledEvaluationRunRequest, + dict, + ], +) +def test_update_scheduled_evaluation_run(request_type, transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scheduled_evaluation_run), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.ScheduledEvaluationRun( + name="name_value", + display_name="display_name_value", + description="description_value", + active=True, + last_completed_run="last_completed_run_value", + total_executions=1738, + created_by="created_by_value", + last_updated_by="last_updated_by_value", + etag="etag_value", + ) + response = client.update_scheduled_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = evaluation_service.UpdateScheduledEvaluationRunRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.ScheduledEvaluationRun) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.active is True + assert response.last_completed_run == "last_completed_run_value" + assert response.total_executions == 1738 + assert response.created_by == "created_by_value" + assert response.last_updated_by == "last_updated_by_value" + assert response.etag == "etag_value" + + +def test_update_scheduled_evaluation_run_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = evaluation_service.UpdateScheduledEvaluationRunRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scheduled_evaluation_run), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_scheduled_evaluation_run(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.UpdateScheduledEvaluationRunRequest() + + +def test_update_scheduled_evaluation_run_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_scheduled_evaluation_run + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_scheduled_evaluation_run + ] = mock_rpc + request = {} + client.update_scheduled_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_scheduled_evaluation_run(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_scheduled_evaluation_run_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_scheduled_evaluation_run + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_scheduled_evaluation_run + ] = mock_rpc + + request = {} + await client.update_scheduled_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_scheduled_evaluation_run(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_update_scheduled_evaluation_run_async( + transport: str = "grpc_asyncio", + request_type=evaluation_service.UpdateScheduledEvaluationRunRequest, +): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scheduled_evaluation_run), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.ScheduledEvaluationRun( + name="name_value", + display_name="display_name_value", + description="description_value", + active=True, + last_completed_run="last_completed_run_value", + total_executions=1738, + created_by="created_by_value", + last_updated_by="last_updated_by_value", + etag="etag_value", + ) + ) + response = await client.update_scheduled_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = evaluation_service.UpdateScheduledEvaluationRunRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.ScheduledEvaluationRun) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.active is True + assert response.last_completed_run == "last_completed_run_value" + assert response.total_executions == 1738 + assert response.created_by == "created_by_value" + assert response.last_updated_by == "last_updated_by_value" + assert response.etag == "etag_value" + + +@pytest.mark.asyncio +async def test_update_scheduled_evaluation_run_async_from_dict(): + await test_update_scheduled_evaluation_run_async(request_type=dict) + + +def test_update_scheduled_evaluation_run_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.UpdateScheduledEvaluationRunRequest() + + request.scheduled_evaluation_run.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scheduled_evaluation_run), "__call__" + ) as call: + call.return_value = evaluation.ScheduledEvaluationRun() + client.update_scheduled_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "scheduled_evaluation_run.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_scheduled_evaluation_run_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.UpdateScheduledEvaluationRunRequest() + + request.scheduled_evaluation_run.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scheduled_evaluation_run), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.ScheduledEvaluationRun() + ) + await client.update_scheduled_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "scheduled_evaluation_run.name=name_value", + ) in kw["metadata"] + + +def test_update_scheduled_evaluation_run_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scheduled_evaluation_run), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.ScheduledEvaluationRun() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_scheduled_evaluation_run( + scheduled_evaluation_run=evaluation.ScheduledEvaluationRun( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].scheduled_evaluation_run + mock_val = evaluation.ScheduledEvaluationRun(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_scheduled_evaluation_run_flattened_error(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_scheduled_evaluation_run( + evaluation_service.UpdateScheduledEvaluationRunRequest(), + scheduled_evaluation_run=evaluation.ScheduledEvaluationRun( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_scheduled_evaluation_run_flattened_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_scheduled_evaluation_run), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.ScheduledEvaluationRun() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.ScheduledEvaluationRun() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_scheduled_evaluation_run( + scheduled_evaluation_run=evaluation.ScheduledEvaluationRun( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].scheduled_evaluation_run + mock_val = evaluation.ScheduledEvaluationRun(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_scheduled_evaluation_run_flattened_error_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_scheduled_evaluation_run( + evaluation_service.UpdateScheduledEvaluationRunRequest(), + scheduled_evaluation_run=evaluation.ScheduledEvaluationRun( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.DeleteScheduledEvaluationRunRequest, + dict, + ], +) +def test_delete_scheduled_evaluation_run(request_type, transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scheduled_evaluation_run), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_scheduled_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = evaluation_service.DeleteScheduledEvaluationRunRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_scheduled_evaluation_run_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = evaluation_service.DeleteScheduledEvaluationRunRequest( + name="name_value", + etag="etag_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scheduled_evaluation_run), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_scheduled_evaluation_run(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.DeleteScheduledEvaluationRunRequest( + name="name_value", + etag="etag_value", + ) + + +def test_delete_scheduled_evaluation_run_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_scheduled_evaluation_run + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_scheduled_evaluation_run + ] = mock_rpc + request = {} + client.delete_scheduled_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_scheduled_evaluation_run(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_scheduled_evaluation_run_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_scheduled_evaluation_run + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_scheduled_evaluation_run + ] = mock_rpc + + request = {} + await client.delete_scheduled_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_scheduled_evaluation_run(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_scheduled_evaluation_run_async( + transport: str = "grpc_asyncio", + request_type=evaluation_service.DeleteScheduledEvaluationRunRequest, +): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scheduled_evaluation_run), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_scheduled_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = evaluation_service.DeleteScheduledEvaluationRunRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_scheduled_evaluation_run_async_from_dict(): + await test_delete_scheduled_evaluation_run_async(request_type=dict) + + +def test_delete_scheduled_evaluation_run_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.DeleteScheduledEvaluationRunRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scheduled_evaluation_run), "__call__" + ) as call: + call.return_value = None + client.delete_scheduled_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_scheduled_evaluation_run_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.DeleteScheduledEvaluationRunRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scheduled_evaluation_run), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_scheduled_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_scheduled_evaluation_run_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scheduled_evaluation_run), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_scheduled_evaluation_run( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_scheduled_evaluation_run_flattened_error(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_scheduled_evaluation_run( + evaluation_service.DeleteScheduledEvaluationRunRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_scheduled_evaluation_run_flattened_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_scheduled_evaluation_run), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_scheduled_evaluation_run( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_scheduled_evaluation_run_flattened_error_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_scheduled_evaluation_run( + evaluation_service.DeleteScheduledEvaluationRunRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.TestPersonaVoiceRequest, + dict, + ], +) +def test_test_persona_voice(request_type, transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_persona_voice), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_service.TestPersonaVoiceResponse( + audio=b"audio_blob", + ) + response = client.test_persona_voice(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = evaluation_service.TestPersonaVoiceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation_service.TestPersonaVoiceResponse) + assert response.audio == b"audio_blob" + + +def test_test_persona_voice_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = evaluation_service.TestPersonaVoiceRequest( + app="app_value", + persona_id="persona_id_value", + text="text_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_persona_voice), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.test_persona_voice(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == evaluation_service.TestPersonaVoiceRequest( + app="app_value", + persona_id="persona_id_value", + text="text_value", + ) + + +def test_test_persona_voice_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.test_persona_voice in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.test_persona_voice] = ( + mock_rpc + ) + request = {} + client.test_persona_voice(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.test_persona_voice(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_test_persona_voice_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.test_persona_voice + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.test_persona_voice + ] = mock_rpc + + request = {} + await client.test_persona_voice(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.test_persona_voice(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_test_persona_voice_async( + transport: str = "grpc_asyncio", + request_type=evaluation_service.TestPersonaVoiceRequest, +): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_persona_voice), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.TestPersonaVoiceResponse( + audio=b"audio_blob", + ) + ) + response = await client.test_persona_voice(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = evaluation_service.TestPersonaVoiceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation_service.TestPersonaVoiceResponse) + assert response.audio == b"audio_blob" + + +@pytest.mark.asyncio +async def test_test_persona_voice_async_from_dict(): + await test_test_persona_voice_async(request_type=dict) + + +def test_test_persona_voice_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.TestPersonaVoiceRequest() + + request.app = "app_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_persona_voice), "__call__" + ) as call: + call.return_value = evaluation_service.TestPersonaVoiceResponse() + client.test_persona_voice(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "app=app_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_persona_voice_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = evaluation_service.TestPersonaVoiceRequest() + + request.app = "app_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_persona_voice), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.TestPersonaVoiceResponse() + ) + await client.test_persona_voice(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "app=app_value", + ) in kw["metadata"] + + +def test_test_persona_voice_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_persona_voice), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_service.TestPersonaVoiceResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.test_persona_voice( + app="app_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].app + mock_val = "app_value" + assert arg == mock_val + + +def test_test_persona_voice_flattened_error(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.test_persona_voice( + evaluation_service.TestPersonaVoiceRequest(), + app="app_value", + ) + + +@pytest.mark.asyncio +async def test_test_persona_voice_flattened_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_persona_voice), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation_service.TestPersonaVoiceResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.TestPersonaVoiceResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.test_persona_voice( + app="app_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].app + mock_val = "app_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_test_persona_voice_flattened_error_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.test_persona_voice( + evaluation_service.TestPersonaVoiceRequest(), + app="app_value", + ) + + +def test_run_evaluation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.run_evaluation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.run_evaluation] = mock_rpc + + request = {} + client.run_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.run_evaluation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_run_evaluation_rest_required_fields( + request_type=evaluation.RunEvaluationRequest, +): + transport_class = transports.EvaluationServiceRestTransport + + request_init = {} + request_init["app"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).run_evaluation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["app"] = "app_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).run_evaluation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "app" in jsonified_request + assert jsonified_request["app"] == "app_value" + + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.run_evaluation(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_run_evaluation_rest_unset_required_fields(): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.run_evaluation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("app",))) + + +def test_run_evaluation_rest_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"app": "projects/sample1/locations/sample2/apps/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + app="app_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.run_evaluation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{app=projects/*/locations/*/apps/*}:runEvaluation" + % client.transport._host, + args[1], + ) + + +def test_run_evaluation_rest_flattened_error(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.run_evaluation( + evaluation.RunEvaluationRequest(), + app="app_value", + ) + + +def test_upload_evaluation_audio_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.upload_evaluation_audio + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.upload_evaluation_audio + ] = mock_rpc + + request = {} + client.upload_evaluation_audio(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.upload_evaluation_audio(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_upload_evaluation_audio_rest_required_fields( + request_type=evaluation_service.UploadEvaluationAudioRequest, +): + transport_class = transports.EvaluationServiceRestTransport + + request_init = {} + request_init["app"] = "" + request_init["audio_content"] = b"" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).upload_evaluation_audio._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["app"] = "app_value" + jsonified_request["audioContent"] = b"audio_content_blob" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).upload_evaluation_audio._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "app" in jsonified_request + assert jsonified_request["app"] == "app_value" + assert "audioContent" in jsonified_request + assert jsonified_request["audioContent"] == b"audio_content_blob" + + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = evaluation_service.UploadEvaluationAudioResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = evaluation_service.UploadEvaluationAudioResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.upload_evaluation_audio(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_upload_evaluation_audio_rest_unset_required_fields(): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.upload_evaluation_audio._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "app", + "audioContent", + ) + ) + ) + + +def test_upload_evaluation_audio_rest_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation_service.UploadEvaluationAudioResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"app": "projects/sample1/locations/sample2/apps/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + app="app_value", + audio_content=b"audio_content_blob", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = evaluation_service.UploadEvaluationAudioResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.upload_evaluation_audio(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{app=projects/*/locations/*/apps/*}:uploadEvaluationAudio" + % client.transport._host, + args[1], + ) + + +def test_upload_evaluation_audio_rest_flattened_error(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.upload_evaluation_audio( + evaluation_service.UploadEvaluationAudioRequest(), + app="app_value", + audio_content=b"audio_content_blob", + ) + + +def test_create_evaluation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_evaluation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_evaluation] = ( + mock_rpc + ) + + request = {} + client.create_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_evaluation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_evaluation_rest_required_fields( + request_type=evaluation_service.CreateEvaluationRequest, +): + transport_class = transports.EvaluationServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_evaluation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_evaluation._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("evaluation_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcc_evaluation.Evaluation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcc_evaluation.Evaluation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_evaluation(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_evaluation_rest_unset_required_fields(): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_evaluation._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("evaluationId",)) + & set( + ( + "parent", + "evaluation", + ) + ) + ) + + +def test_create_evaluation_rest_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcc_evaluation.Evaluation() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + evaluation=gcc_evaluation.Evaluation( + golden=gcc_evaluation.Evaluation.Golden( + turns=[ + gcc_evaluation.Evaluation.GoldenTurn( + steps=[ + gcc_evaluation.Evaluation.Step( + user_input=session_service.SessionInput( + text="text_value" + ) + ) + ] + ) + ] + ) + ), + evaluation_id="evaluation_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcc_evaluation.Evaluation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_evaluation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*/apps/*}/evaluations" + % client.transport._host, + args[1], + ) + + +def test_create_evaluation_rest_flattened_error(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_evaluation( + evaluation_service.CreateEvaluationRequest(), + parent="parent_value", + evaluation=gcc_evaluation.Evaluation( + golden=gcc_evaluation.Evaluation.Golden( + turns=[ + gcc_evaluation.Evaluation.GoldenTurn( + steps=[ + gcc_evaluation.Evaluation.Step( + user_input=session_service.SessionInput( + text="text_value" + ) + ) + ] + ) + ] + ) + ), + evaluation_id="evaluation_id_value", + ) + + +def test_generate_evaluation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.generate_evaluation in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.generate_evaluation] = ( + mock_rpc + ) + + request = {} + client.generate_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.generate_evaluation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_generate_evaluation_rest_required_fields( + request_type=evaluation_service.GenerateEvaluationRequest, +): + transport_class = transports.EvaluationServiceRestTransport + + request_init = {} + request_init["conversation"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).generate_evaluation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["conversation"] = "conversation_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).generate_evaluation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "conversation" in jsonified_request + assert jsonified_request["conversation"] == "conversation_value" + + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.generate_evaluation(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_generate_evaluation_rest_unset_required_fields(): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.generate_evaluation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("conversation",))) + + +def test_generate_evaluation_rest_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "conversation": "projects/sample1/locations/sample2/apps/sample3/conversations/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + conversation="conversation_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.generate_evaluation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{conversation=projects/*/locations/*/apps/*/conversations/*}:generateEvaluation" + % client.transport._host, + args[1], + ) + + +def test_generate_evaluation_rest_flattened_error(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.generate_evaluation( + evaluation_service.GenerateEvaluationRequest(), + conversation="conversation_value", + ) + + +def test_import_evaluations_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.import_evaluations in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.import_evaluations] = ( + mock_rpc + ) + + request = {} + client.import_evaluations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.import_evaluations(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_import_evaluations_rest_required_fields( + request_type=evaluation_service.ImportEvaluationsRequest, +): + transport_class = transports.EvaluationServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).import_evaluations._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).import_evaluations._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.import_evaluations(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_import_evaluations_rest_unset_required_fields(): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.import_evaluations._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent",))) + + +def test_import_evaluations_rest_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.import_evaluations(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*/apps/*}:importEvaluations" + % client.transport._host, + args[1], + ) + + +def test_import_evaluations_rest_flattened_error(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.import_evaluations( + evaluation_service.ImportEvaluationsRequest(), + parent="parent_value", + ) + + +def test_create_evaluation_dataset_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_evaluation_dataset + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_evaluation_dataset + ] = mock_rpc + + request = {} + client.create_evaluation_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_evaluation_dataset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_evaluation_dataset_rest_required_fields( + request_type=evaluation_service.CreateEvaluationDatasetRequest, +): + transport_class = transports.EvaluationServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_evaluation_dataset._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_evaluation_dataset._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("evaluation_dataset_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = evaluation.EvaluationDataset() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = evaluation.EvaluationDataset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_evaluation_dataset(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_evaluation_dataset_rest_unset_required_fields(): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_evaluation_dataset._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("evaluationDatasetId",)) + & set( + ( + "parent", + "evaluationDataset", + ) + ) + ) + + +def test_create_evaluation_dataset_rest_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation.EvaluationDataset() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + evaluation_dataset=evaluation.EvaluationDataset(name="name_value"), + evaluation_dataset_id="evaluation_dataset_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = evaluation.EvaluationDataset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_evaluation_dataset(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*/apps/*}/evaluationDatasets" + % client.transport._host, + args[1], + ) + + +def test_create_evaluation_dataset_rest_flattened_error(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_evaluation_dataset( + evaluation_service.CreateEvaluationDatasetRequest(), + parent="parent_value", + evaluation_dataset=evaluation.EvaluationDataset(name="name_value"), + evaluation_dataset_id="evaluation_dataset_id_value", + ) + + +def test_update_evaluation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_evaluation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_evaluation] = ( + mock_rpc + ) + + request = {} + client.update_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_evaluation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_evaluation_rest_required_fields( + request_type=evaluation_service.UpdateEvaluationRequest, +): + transport_class = transports.EvaluationServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_evaluation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_evaluation._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcc_evaluation.Evaluation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcc_evaluation.Evaluation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_evaluation(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_evaluation_rest_unset_required_fields(): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_evaluation._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("evaluation",))) + + +def test_update_evaluation_rest_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcc_evaluation.Evaluation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "evaluation": { + "name": "projects/sample1/locations/sample2/apps/sample3/evaluations/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + evaluation=gcc_evaluation.Evaluation( + golden=gcc_evaluation.Evaluation.Golden( + turns=[ + gcc_evaluation.Evaluation.GoldenTurn( + steps=[ + gcc_evaluation.Evaluation.Step( + user_input=session_service.SessionInput( + text="text_value" + ) + ) + ] + ) + ] + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = gcc_evaluation.Evaluation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_evaluation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{evaluation.name=projects/*/locations/*/apps/*/evaluations/*}" + % client.transport._host, + args[1], + ) + + +def test_update_evaluation_rest_flattened_error(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_evaluation( + evaluation_service.UpdateEvaluationRequest(), + evaluation=gcc_evaluation.Evaluation( + golden=gcc_evaluation.Evaluation.Golden( + turns=[ + gcc_evaluation.Evaluation.GoldenTurn( + steps=[ + gcc_evaluation.Evaluation.Step( + user_input=session_service.SessionInput( + text="text_value" + ) + ) + ] + ) + ] + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_evaluation_dataset_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_evaluation_dataset + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_evaluation_dataset + ] = mock_rpc + + request = {} + client.update_evaluation_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_evaluation_dataset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_evaluation_dataset_rest_required_fields( + request_type=evaluation_service.UpdateEvaluationDatasetRequest, +): + transport_class = transports.EvaluationServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_evaluation_dataset._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_evaluation_dataset._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = evaluation.EvaluationDataset() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = evaluation.EvaluationDataset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_evaluation_dataset(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_evaluation_dataset_rest_unset_required_fields(): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_evaluation_dataset._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("evaluationDataset",))) + + +def test_update_evaluation_dataset_rest_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation.EvaluationDataset() + + # get arguments that satisfy an http rule for this method + sample_request = { + "evaluation_dataset": { + "name": "projects/sample1/locations/sample2/apps/sample3/evaluationDatasets/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + evaluation_dataset=evaluation.EvaluationDataset(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = evaluation.EvaluationDataset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_evaluation_dataset(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{evaluation_dataset.name=projects/*/locations/*/apps/*/evaluationDatasets/*}" + % client.transport._host, + args[1], + ) + + +def test_update_evaluation_dataset_rest_flattened_error(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_evaluation_dataset( + evaluation_service.UpdateEvaluationDatasetRequest(), + evaluation_dataset=evaluation.EvaluationDataset(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_evaluation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_evaluation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_evaluation] = ( + mock_rpc + ) + + request = {} + client.delete_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_evaluation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_evaluation_rest_required_fields( + request_type=evaluation_service.DeleteEvaluationRequest, +): + transport_class = transports.EvaluationServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_evaluation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_evaluation._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "etag", + "force", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_evaluation(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_evaluation_rest_unset_required_fields(): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_evaluation._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "etag", + "force", + ) + ) + & set(("name",)) + ) + + +def test_delete_evaluation_rest_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/apps/sample3/evaluations/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_evaluation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/apps/*/evaluations/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_evaluation_rest_flattened_error(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_evaluation( + evaluation_service.DeleteEvaluationRequest(), + name="name_value", + ) + + +def test_delete_evaluation_result_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_evaluation_result + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_evaluation_result + ] = mock_rpc + + request = {} + client.delete_evaluation_result(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_evaluation_result(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_evaluation_result_rest_required_fields( + request_type=evaluation_service.DeleteEvaluationResultRequest, +): + transport_class = transports.EvaluationServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_evaluation_result._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_evaluation_result._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_evaluation_result(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_evaluation_result_rest_unset_required_fields(): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_evaluation_result._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_delete_evaluation_result_rest_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/apps/sample3/evaluations/sample4/results/sample5" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_evaluation_result(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/apps/*/evaluations/*/results/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_evaluation_result_rest_flattened_error(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_evaluation_result( + evaluation_service.DeleteEvaluationResultRequest(), + name="name_value", + ) + + +def test_delete_evaluation_dataset_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_evaluation_dataset + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_evaluation_dataset + ] = mock_rpc + + request = {} + client.delete_evaluation_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_evaluation_dataset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_evaluation_dataset_rest_required_fields( + request_type=evaluation_service.DeleteEvaluationDatasetRequest, +): + transport_class = transports.EvaluationServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_evaluation_dataset._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_evaluation_dataset._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("etag",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_evaluation_dataset(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_evaluation_dataset_rest_unset_required_fields(): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_evaluation_dataset._get_unset_required_fields({}) + assert set(unset_fields) == (set(("etag",)) & set(("name",))) + + +def test_delete_evaluation_dataset_rest_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/apps/sample3/evaluationDatasets/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_evaluation_dataset(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/apps/*/evaluationDatasets/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_evaluation_dataset_rest_flattened_error(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_evaluation_dataset( + evaluation_service.DeleteEvaluationDatasetRequest(), + name="name_value", + ) + + +def test_delete_evaluation_run_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_evaluation_run + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_evaluation_run] = ( + mock_rpc + ) + + request = {} + client.delete_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_evaluation_run(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_evaluation_run_rest_required_fields( + request_type=evaluation_service.DeleteEvaluationRunRequest, +): + transport_class = transports.EvaluationServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_evaluation_run._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_evaluation_run._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_evaluation_run(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_evaluation_run_rest_unset_required_fields(): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_evaluation_run._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_delete_evaluation_run_rest_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/apps/sample3/evaluationRuns/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_evaluation_run(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/apps/*/evaluationRuns/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_evaluation_run_rest_flattened_error(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_evaluation_run( + evaluation_service.DeleteEvaluationRunRequest(), + name="name_value", + ) + + +def test_get_evaluation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_evaluation in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_evaluation] = mock_rpc + + request = {} + client.get_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_evaluation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_evaluation_rest_required_fields( + request_type=evaluation_service.GetEvaluationRequest, +): + transport_class = transports.EvaluationServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_evaluation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_evaluation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = evaluation.Evaluation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = evaluation.Evaluation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_evaluation(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_evaluation_rest_unset_required_fields(): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_evaluation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_evaluation_rest_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation.Evaluation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/apps/sample3/evaluations/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = evaluation.Evaluation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_evaluation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/apps/*/evaluations/*}" + % client.transport._host, + args[1], + ) + + +def test_get_evaluation_rest_flattened_error(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_evaluation( + evaluation_service.GetEvaluationRequest(), + name="name_value", + ) + + +def test_get_evaluation_result_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_evaluation_result + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_evaluation_result] = ( + mock_rpc + ) + + request = {} + client.get_evaluation_result(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_evaluation_result(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_evaluation_result_rest_required_fields( + request_type=evaluation_service.GetEvaluationResultRequest, +): + transport_class = transports.EvaluationServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_evaluation_result._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_evaluation_result._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = evaluation.EvaluationResult() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = evaluation.EvaluationResult.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_evaluation_result(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_evaluation_result_rest_unset_required_fields(): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_evaluation_result._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_evaluation_result_rest_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation.EvaluationResult() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/apps/sample3/evaluations/sample4/results/sample5" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = evaluation.EvaluationResult.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_evaluation_result(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/apps/*/evaluations/*/results/*}" + % client.transport._host, + args[1], + ) + + +def test_get_evaluation_result_rest_flattened_error(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_evaluation_result( + evaluation_service.GetEvaluationResultRequest(), + name="name_value", + ) + + +def test_get_evaluation_dataset_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_evaluation_dataset + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_evaluation_dataset] = ( + mock_rpc + ) + + request = {} + client.get_evaluation_dataset(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_evaluation_dataset(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_evaluation_dataset_rest_required_fields( + request_type=evaluation_service.GetEvaluationDatasetRequest, +): + transport_class = transports.EvaluationServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_evaluation_dataset._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_evaluation_dataset._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = evaluation.EvaluationDataset() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = evaluation.EvaluationDataset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_evaluation_dataset(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_evaluation_dataset_rest_unset_required_fields(): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_evaluation_dataset._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_evaluation_dataset_rest_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation.EvaluationDataset() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/apps/sample3/evaluationDatasets/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = evaluation.EvaluationDataset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_evaluation_dataset(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/apps/*/evaluationDatasets/*}" + % client.transport._host, + args[1], + ) + + +def test_get_evaluation_dataset_rest_flattened_error(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_evaluation_dataset( + evaluation_service.GetEvaluationDatasetRequest(), + name="name_value", + ) + + +def test_get_evaluation_run_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_evaluation_run in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_evaluation_run] = ( + mock_rpc + ) + + request = {} + client.get_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_evaluation_run(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_evaluation_run_rest_required_fields( + request_type=evaluation_service.GetEvaluationRunRequest, +): + transport_class = transports.EvaluationServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_evaluation_run._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_evaluation_run._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = evaluation.EvaluationRun() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = evaluation.EvaluationRun.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_evaluation_run(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_evaluation_run_rest_unset_required_fields(): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_evaluation_run._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_evaluation_run_rest_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation.EvaluationRun() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/apps/sample3/evaluationRuns/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = evaluation.EvaluationRun.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_evaluation_run(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/apps/*/evaluationRuns/*}" + % client.transport._host, + args[1], + ) + + +def test_get_evaluation_run_rest_flattened_error(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_evaluation_run( + evaluation_service.GetEvaluationRunRequest(), + name="name_value", + ) + + +def test_list_evaluations_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_evaluations in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_evaluations] = ( + mock_rpc + ) + + request = {} + client.list_evaluations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_evaluations(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_evaluations_rest_required_fields( + request_type=evaluation_service.ListEvaluationsRequest, +): + transport_class = transports.EvaluationServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_evaluations._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_evaluations._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "evaluation_filter", + "evaluation_run_filter", + "filter", + "last_ten_results", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = evaluation_service.ListEvaluationsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = evaluation_service.ListEvaluationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_evaluations(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_evaluations_rest_unset_required_fields(): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_evaluations._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "evaluationFilter", + "evaluationRunFilter", + "filter", + "lastTenResults", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_evaluations_rest_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation_service.ListEvaluationsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = evaluation_service.ListEvaluationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_evaluations(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*/apps/*}/evaluations" + % client.transport._host, + args[1], + ) + + +def test_list_evaluations_rest_flattened_error(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_evaluations( + evaluation_service.ListEvaluationsRequest(), + parent="parent_value", + ) + + +def test_list_evaluations_rest_pager(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + evaluation_service.ListEvaluationsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + pager = client.list_evaluations(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, evaluation.Evaluation) for i in results) + + pages = list(client.list_evaluations(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_list_evaluation_results_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_evaluation_results + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_evaluation_results + ] = mock_rpc + + request = {} + client.list_evaluation_results(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_evaluation_results(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_evaluation_results_rest_required_fields( + request_type=evaluation_service.ListEvaluationResultsRequest, +): + transport_class = transports.EvaluationServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_evaluation_results._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_evaluation_results._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = evaluation_service.ListEvaluationResultsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = evaluation_service.ListEvaluationResultsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_evaluation_results(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_evaluation_results_rest_unset_required_fields(): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_evaluation_results._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_evaluation_results_rest_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation_service.ListEvaluationResultsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/apps/sample3/evaluations/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = evaluation_service.ListEvaluationResultsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_evaluation_results(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*/apps/*/evaluations/*}/results" + % client.transport._host, + args[1], + ) + + +def test_list_evaluation_results_rest_flattened_error(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_evaluation_results( + evaluation_service.ListEvaluationResultsRequest(), + parent="parent_value", + ) + + +def test_list_evaluation_results_rest_pager(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation.EvaluationResult(), + evaluation.EvaluationResult(), + evaluation.EvaluationResult(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation.EvaluationResult(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationResultsResponse( + evaluation_results=[ + evaluation.EvaluationResult(), + evaluation.EvaluationResult(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + evaluation_service.ListEvaluationResultsResponse.to_json(x) + for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "projects/sample1/locations/sample2/apps/sample3/evaluations/sample4" + } + + pager = client.list_evaluation_results(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, evaluation.EvaluationResult) for i in results) + + pages = list(client.list_evaluation_results(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_list_evaluation_datasets_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_evaluation_datasets + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_evaluation_datasets + ] = mock_rpc + + request = {} + client.list_evaluation_datasets(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_evaluation_datasets(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_evaluation_datasets_rest_required_fields( + request_type=evaluation_service.ListEvaluationDatasetsRequest, +): + transport_class = transports.EvaluationServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_evaluation_datasets._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_evaluation_datasets._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = evaluation_service.ListEvaluationDatasetsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = evaluation_service.ListEvaluationDatasetsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_evaluation_datasets(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_evaluation_datasets_rest_unset_required_fields(): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_evaluation_datasets._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_evaluation_datasets_rest_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation_service.ListEvaluationDatasetsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = evaluation_service.ListEvaluationDatasetsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_evaluation_datasets(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*/apps/*}/evaluationDatasets" + % client.transport._host, + args[1], + ) + + +def test_list_evaluation_datasets_rest_flattened_error(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_evaluation_datasets( + evaluation_service.ListEvaluationDatasetsRequest(), + parent="parent_value", + ) + + +def test_list_evaluation_datasets_rest_pager(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + evaluation_service.ListEvaluationDatasetsResponse( + evaluation_datasets=[ + evaluation.EvaluationDataset(), + evaluation.EvaluationDataset(), + evaluation.EvaluationDataset(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationDatasetsResponse( + evaluation_datasets=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationDatasetsResponse( + evaluation_datasets=[ + evaluation.EvaluationDataset(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationDatasetsResponse( + evaluation_datasets=[ + evaluation.EvaluationDataset(), + evaluation.EvaluationDataset(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + evaluation_service.ListEvaluationDatasetsResponse.to_json(x) + for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + pager = client.list_evaluation_datasets(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, evaluation.EvaluationDataset) for i in results) + + pages = list(client.list_evaluation_datasets(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_list_evaluation_runs_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_evaluation_runs in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_evaluation_runs] = ( + mock_rpc + ) + + request = {} + client.list_evaluation_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_evaluation_runs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_evaluation_runs_rest_required_fields( + request_type=evaluation_service.ListEvaluationRunsRequest, +): + transport_class = transports.EvaluationServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_evaluation_runs._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_evaluation_runs._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = evaluation_service.ListEvaluationRunsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = evaluation_service.ListEvaluationRunsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_evaluation_runs(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_evaluation_runs_rest_unset_required_fields(): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_evaluation_runs._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_evaluation_runs_rest_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation_service.ListEvaluationRunsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = evaluation_service.ListEvaluationRunsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_evaluation_runs(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*/apps/*}/evaluationRuns" + % client.transport._host, + args[1], + ) + + +def test_list_evaluation_runs_rest_flattened_error(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_evaluation_runs( + evaluation_service.ListEvaluationRunsRequest(), + parent="parent_value", + ) + + +def test_list_evaluation_runs_rest_pager(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + evaluation_service.ListEvaluationRunsResponse( + evaluation_runs=[ + evaluation.EvaluationRun(), + evaluation.EvaluationRun(), + evaluation.EvaluationRun(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationRunsResponse( + evaluation_runs=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationRunsResponse( + evaluation_runs=[ + evaluation.EvaluationRun(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationRunsResponse( + evaluation_runs=[ + evaluation.EvaluationRun(), + evaluation.EvaluationRun(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + evaluation_service.ListEvaluationRunsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + pager = client.list_evaluation_runs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, evaluation.EvaluationRun) for i in results) + + pages = list(client.list_evaluation_runs(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_list_evaluation_expectations_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_evaluation_expectations + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_evaluation_expectations + ] = mock_rpc + + request = {} + client.list_evaluation_expectations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_evaluation_expectations(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_evaluation_expectations_rest_required_fields( + request_type=evaluation_service.ListEvaluationExpectationsRequest, +): + transport_class = transports.EvaluationServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_evaluation_expectations._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_evaluation_expectations._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = evaluation_service.ListEvaluationExpectationsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = evaluation_service.ListEvaluationExpectationsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_evaluation_expectations(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_evaluation_expectations_rest_unset_required_fields(): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_evaluation_expectations._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_evaluation_expectations_rest_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation_service.ListEvaluationExpectationsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = evaluation_service.ListEvaluationExpectationsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_evaluation_expectations(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*/apps/*}/evaluationExpectations" + % client.transport._host, + args[1], + ) + + +def test_list_evaluation_expectations_rest_flattened_error(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_evaluation_expectations( + evaluation_service.ListEvaluationExpectationsRequest(), + parent="parent_value", + ) + + +def test_list_evaluation_expectations_rest_pager(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + evaluation_service.ListEvaluationExpectationsResponse( + evaluation_expectations=[ + evaluation.EvaluationExpectation(), + evaluation.EvaluationExpectation(), + evaluation.EvaluationExpectation(), + ], + next_page_token="abc", + ), + evaluation_service.ListEvaluationExpectationsResponse( + evaluation_expectations=[], + next_page_token="def", + ), + evaluation_service.ListEvaluationExpectationsResponse( + evaluation_expectations=[ + evaluation.EvaluationExpectation(), + ], + next_page_token="ghi", + ), + evaluation_service.ListEvaluationExpectationsResponse( + evaluation_expectations=[ + evaluation.EvaluationExpectation(), + evaluation.EvaluationExpectation(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + evaluation_service.ListEvaluationExpectationsResponse.to_json(x) + for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + pager = client.list_evaluation_expectations(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, evaluation.EvaluationExpectation) for i in results) + + pages = list(client.list_evaluation_expectations(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_evaluation_expectation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_evaluation_expectation + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_evaluation_expectation + ] = mock_rpc + + request = {} + client.get_evaluation_expectation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_evaluation_expectation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_evaluation_expectation_rest_required_fields( + request_type=evaluation_service.GetEvaluationExpectationRequest, +): + transport_class = transports.EvaluationServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_evaluation_expectation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_evaluation_expectation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = evaluation.EvaluationExpectation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = evaluation.EvaluationExpectation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_evaluation_expectation(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_evaluation_expectation_rest_unset_required_fields(): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_evaluation_expectation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_evaluation_expectation_rest_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation.EvaluationExpectation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/apps/sample3/evaluationExpectations/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = evaluation.EvaluationExpectation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_evaluation_expectation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/apps/*/evaluationExpectations/*}" + % client.transport._host, + args[1], + ) + + +def test_get_evaluation_expectation_rest_flattened_error(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_evaluation_expectation( + evaluation_service.GetEvaluationExpectationRequest(), + name="name_value", + ) + + +def test_create_evaluation_expectation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_evaluation_expectation + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_evaluation_expectation + ] = mock_rpc + + request = {} + client.create_evaluation_expectation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_evaluation_expectation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_evaluation_expectation_rest_required_fields( + request_type=evaluation_service.CreateEvaluationExpectationRequest, +): + transport_class = transports.EvaluationServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_evaluation_expectation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_evaluation_expectation._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("evaluation_expectation_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = evaluation.EvaluationExpectation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = evaluation.EvaluationExpectation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_evaluation_expectation(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_evaluation_expectation_rest_unset_required_fields(): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_evaluation_expectation._get_unset_required_fields( + {} + ) + assert set(unset_fields) == ( + set(("evaluationExpectationId",)) + & set( + ( + "parent", + "evaluationExpectation", + ) + ) + ) + + +def test_create_evaluation_expectation_rest_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation.EvaluationExpectation() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + evaluation_expectation=evaluation.EvaluationExpectation( + llm_criteria=evaluation.EvaluationExpectation.LlmCriteria( + prompt="prompt_value" + ) + ), + evaluation_expectation_id="evaluation_expectation_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = evaluation.EvaluationExpectation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_evaluation_expectation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*/apps/*}/evaluationExpectations" + % client.transport._host, + args[1], + ) + + +def test_create_evaluation_expectation_rest_flattened_error(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_evaluation_expectation( + evaluation_service.CreateEvaluationExpectationRequest(), + parent="parent_value", + evaluation_expectation=evaluation.EvaluationExpectation( + llm_criteria=evaluation.EvaluationExpectation.LlmCriteria( + prompt="prompt_value" + ) + ), + evaluation_expectation_id="evaluation_expectation_id_value", + ) + + +def test_update_evaluation_expectation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_evaluation_expectation + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_evaluation_expectation + ] = mock_rpc + + request = {} + client.update_evaluation_expectation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_evaluation_expectation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_evaluation_expectation_rest_required_fields( + request_type=evaluation_service.UpdateEvaluationExpectationRequest, +): + transport_class = transports.EvaluationServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_evaluation_expectation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_evaluation_expectation._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = evaluation.EvaluationExpectation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = evaluation.EvaluationExpectation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_evaluation_expectation(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_evaluation_expectation_rest_unset_required_fields(): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_evaluation_expectation._get_unset_required_fields( + {} + ) + assert set(unset_fields) == (set(("updateMask",)) & set(("evaluationExpectation",))) + + +def test_update_evaluation_expectation_rest_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation.EvaluationExpectation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "evaluation_expectation": { + "name": "projects/sample1/locations/sample2/apps/sample3/evaluationExpectations/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + evaluation_expectation=evaluation.EvaluationExpectation( + llm_criteria=evaluation.EvaluationExpectation.LlmCriteria( + prompt="prompt_value" + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = evaluation.EvaluationExpectation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_evaluation_expectation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{evaluation_expectation.name=projects/*/locations/*/apps/*/evaluationExpectations/*}" + % client.transport._host, + args[1], + ) + + +def test_update_evaluation_expectation_rest_flattened_error(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_evaluation_expectation( + evaluation_service.UpdateEvaluationExpectationRequest(), + evaluation_expectation=evaluation.EvaluationExpectation( + llm_criteria=evaluation.EvaluationExpectation.LlmCriteria( + prompt="prompt_value" + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_evaluation_expectation_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_evaluation_expectation + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_evaluation_expectation + ] = mock_rpc + + request = {} + client.delete_evaluation_expectation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_evaluation_expectation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_evaluation_expectation_rest_required_fields( + request_type=evaluation_service.DeleteEvaluationExpectationRequest, +): + transport_class = transports.EvaluationServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_evaluation_expectation._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_evaluation_expectation._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("etag",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_evaluation_expectation(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_evaluation_expectation_rest_unset_required_fields(): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_evaluation_expectation._get_unset_required_fields( + {} + ) + assert set(unset_fields) == (set(("etag",)) & set(("name",))) + + +def test_delete_evaluation_expectation_rest_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/apps/sample3/evaluationExpectations/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_evaluation_expectation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/apps/*/evaluationExpectations/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_evaluation_expectation_rest_flattened_error(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_evaluation_expectation( + evaluation_service.DeleteEvaluationExpectationRequest(), + name="name_value", + ) + + +def test_create_scheduled_evaluation_run_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_scheduled_evaluation_run + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_scheduled_evaluation_run + ] = mock_rpc + + request = {} + client.create_scheduled_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_scheduled_evaluation_run(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_scheduled_evaluation_run_rest_required_fields( + request_type=evaluation_service.CreateScheduledEvaluationRunRequest, +): + transport_class = transports.EvaluationServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_scheduled_evaluation_run._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_scheduled_evaluation_run._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("scheduled_evaluation_run_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = evaluation.ScheduledEvaluationRun() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = evaluation.ScheduledEvaluationRun.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_scheduled_evaluation_run(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_scheduled_evaluation_run_rest_unset_required_fields(): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_scheduled_evaluation_run._get_unset_required_fields( + {} + ) + assert set(unset_fields) == ( + set(("scheduledEvaluationRunId",)) + & set( + ( + "parent", + "scheduledEvaluationRun", + ) + ) + ) + + +def test_create_scheduled_evaluation_run_rest_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation.ScheduledEvaluationRun() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + scheduled_evaluation_run=evaluation.ScheduledEvaluationRun( + name="name_value" + ), + scheduled_evaluation_run_id="scheduled_evaluation_run_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = evaluation.ScheduledEvaluationRun.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_scheduled_evaluation_run(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*/apps/*}/scheduledEvaluationRuns" + % client.transport._host, + args[1], + ) + + +def test_create_scheduled_evaluation_run_rest_flattened_error(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_scheduled_evaluation_run( + evaluation_service.CreateScheduledEvaluationRunRequest(), + parent="parent_value", + scheduled_evaluation_run=evaluation.ScheduledEvaluationRun( + name="name_value" + ), + scheduled_evaluation_run_id="scheduled_evaluation_run_id_value", + ) + + +def test_get_scheduled_evaluation_run_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_scheduled_evaluation_run + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_scheduled_evaluation_run + ] = mock_rpc + + request = {} + client.get_scheduled_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_scheduled_evaluation_run(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_scheduled_evaluation_run_rest_required_fields( + request_type=evaluation_service.GetScheduledEvaluationRunRequest, +): + transport_class = transports.EvaluationServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_scheduled_evaluation_run._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_scheduled_evaluation_run._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = evaluation.ScheduledEvaluationRun() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = evaluation.ScheduledEvaluationRun.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_scheduled_evaluation_run(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_scheduled_evaluation_run_rest_unset_required_fields(): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_scheduled_evaluation_run._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_scheduled_evaluation_run_rest_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation.ScheduledEvaluationRun() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/apps/sample3/scheduledEvaluationRuns/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = evaluation.ScheduledEvaluationRun.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get_scheduled_evaluation_run(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/apps/*/scheduledEvaluationRuns/*}" + % client.transport._host, + args[1], + ) + + +def test_get_scheduled_evaluation_run_rest_flattened_error(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_scheduled_evaluation_run( + evaluation_service.GetScheduledEvaluationRunRequest(), + name="name_value", + ) + + +def test_list_scheduled_evaluation_runs_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_scheduled_evaluation_runs + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_scheduled_evaluation_runs + ] = mock_rpc + + request = {} + client.list_scheduled_evaluation_runs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_scheduled_evaluation_runs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_scheduled_evaluation_runs_rest_required_fields( + request_type=evaluation_service.ListScheduledEvaluationRunsRequest, +): + transport_class = transports.EvaluationServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_scheduled_evaluation_runs._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_scheduled_evaluation_runs._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = evaluation_service.ListScheduledEvaluationRunsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = evaluation_service.ListScheduledEvaluationRunsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_scheduled_evaluation_runs(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_scheduled_evaluation_runs_rest_unset_required_fields(): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_scheduled_evaluation_runs._get_unset_required_fields( + {} + ) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_scheduled_evaluation_runs_rest_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation_service.ListScheduledEvaluationRunsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = evaluation_service.ListScheduledEvaluationRunsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list_scheduled_evaluation_runs(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*/apps/*}/scheduledEvaluationRuns" + % client.transport._host, + args[1], + ) + + +def test_list_scheduled_evaluation_runs_rest_flattened_error(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_scheduled_evaluation_runs( + evaluation_service.ListScheduledEvaluationRunsRequest(), + parent="parent_value", + ) + + +def test_list_scheduled_evaluation_runs_rest_pager(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + evaluation_service.ListScheduledEvaluationRunsResponse( + scheduled_evaluation_runs=[ + evaluation.ScheduledEvaluationRun(), + evaluation.ScheduledEvaluationRun(), + evaluation.ScheduledEvaluationRun(), + ], + next_page_token="abc", + ), + evaluation_service.ListScheduledEvaluationRunsResponse( + scheduled_evaluation_runs=[], + next_page_token="def", + ), + evaluation_service.ListScheduledEvaluationRunsResponse( + scheduled_evaluation_runs=[ + evaluation.ScheduledEvaluationRun(), + ], + next_page_token="ghi", + ), + evaluation_service.ListScheduledEvaluationRunsResponse( + scheduled_evaluation_runs=[ + evaluation.ScheduledEvaluationRun(), + evaluation.ScheduledEvaluationRun(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + evaluation_service.ListScheduledEvaluationRunsResponse.to_json(x) + for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + + pager = client.list_scheduled_evaluation_runs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, evaluation.ScheduledEvaluationRun) for i in results) + + pages = list( + client.list_scheduled_evaluation_runs(request=sample_request).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_update_scheduled_evaluation_run_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_scheduled_evaluation_run + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_scheduled_evaluation_run + ] = mock_rpc + + request = {} + client.update_scheduled_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_scheduled_evaluation_run(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_scheduled_evaluation_run_rest_required_fields( + request_type=evaluation_service.UpdateScheduledEvaluationRunRequest, +): + transport_class = transports.EvaluationServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_scheduled_evaluation_run._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_scheduled_evaluation_run._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = evaluation.ScheduledEvaluationRun() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = evaluation.ScheduledEvaluationRun.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_scheduled_evaluation_run(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_scheduled_evaluation_run_rest_unset_required_fields(): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_scheduled_evaluation_run._get_unset_required_fields( + {} + ) + assert set(unset_fields) == ( + set(("updateMask",)) & set(("scheduledEvaluationRun",)) + ) + + +def test_update_scheduled_evaluation_run_rest_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation.ScheduledEvaluationRun() + + # get arguments that satisfy an http rule for this method + sample_request = { + "scheduled_evaluation_run": { + "name": "projects/sample1/locations/sample2/apps/sample3/scheduledEvaluationRuns/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + scheduled_evaluation_run=evaluation.ScheduledEvaluationRun( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = evaluation.ScheduledEvaluationRun.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_scheduled_evaluation_run(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{scheduled_evaluation_run.name=projects/*/locations/*/apps/*/scheduledEvaluationRuns/*}" + % client.transport._host, + args[1], + ) + + +def test_update_scheduled_evaluation_run_rest_flattened_error(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_scheduled_evaluation_run( + evaluation_service.UpdateScheduledEvaluationRunRequest(), + scheduled_evaluation_run=evaluation.ScheduledEvaluationRun( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_scheduled_evaluation_run_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_scheduled_evaluation_run + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.delete_scheduled_evaluation_run + ] = mock_rpc + + request = {} + client.delete_scheduled_evaluation_run(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_scheduled_evaluation_run(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_scheduled_evaluation_run_rest_required_fields( + request_type=evaluation_service.DeleteScheduledEvaluationRunRequest, +): + transport_class = transports.EvaluationServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_scheduled_evaluation_run._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_scheduled_evaluation_run._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("etag",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_scheduled_evaluation_run(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_scheduled_evaluation_run_rest_unset_required_fields(): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_scheduled_evaluation_run._get_unset_required_fields( + {} + ) + assert set(unset_fields) == (set(("etag",)) & set(("name",))) + + +def test_delete_scheduled_evaluation_run_rest_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/apps/sample3/scheduledEvaluationRuns/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_scheduled_evaluation_run(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/apps/*/scheduledEvaluationRuns/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_scheduled_evaluation_run_rest_flattened_error(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_scheduled_evaluation_run( + evaluation_service.DeleteScheduledEvaluationRunRequest(), + name="name_value", + ) + + +def test_test_persona_voice_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.test_persona_voice in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.test_persona_voice] = ( + mock_rpc + ) + + request = {} + client.test_persona_voice(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.test_persona_voice(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_test_persona_voice_rest_required_fields( + request_type=evaluation_service.TestPersonaVoiceRequest, +): + transport_class = transports.EvaluationServiceRestTransport + + request_init = {} + request_init["app"] = "" + request_init["persona_id"] = "" + request_init["text"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).test_persona_voice._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["app"] = "app_value" + jsonified_request["personaId"] = "persona_id_value" + jsonified_request["text"] = "text_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).test_persona_voice._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "app" in jsonified_request + assert jsonified_request["app"] == "app_value" + assert "personaId" in jsonified_request + assert jsonified_request["personaId"] == "persona_id_value" + assert "text" in jsonified_request + assert jsonified_request["text"] == "text_value" + + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = evaluation_service.TestPersonaVoiceResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = evaluation_service.TestPersonaVoiceResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.test_persona_voice(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_test_persona_voice_rest_unset_required_fields(): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.test_persona_voice._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "app", + "personaId", + "text", + ) + ) + ) + + +def test_test_persona_voice_rest_flattened(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation_service.TestPersonaVoiceResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"app": "projects/sample1/locations/sample2/apps/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + app="app_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = evaluation_service.TestPersonaVoiceResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.test_persona_voice(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{app=projects/*/locations/*/apps/*}:testPersonaVoice" + % client.transport._host, + args[1], + ) + + +def test_test_persona_voice_rest_flattened_error(transport: str = "rest"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.test_persona_voice( + evaluation_service.TestPersonaVoiceRequest(), + app="app_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.EvaluationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.EvaluationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EvaluationServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.EvaluationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = EvaluationServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = EvaluationServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.EvaluationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EvaluationServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.EvaluationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = EvaluationServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.EvaluationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.EvaluationServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.EvaluationServiceGrpcTransport, + transports.EvaluationServiceGrpcAsyncIOTransport, + transports.EvaluationServiceRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_kind_grpc(): + transport = EvaluationServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_run_evaluation_empty_call_grpc(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.run_evaluation), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.run_evaluation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation.RunEvaluationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_upload_evaluation_audio_empty_call_grpc(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.upload_evaluation_audio), "__call__" + ) as call: + call.return_value = evaluation_service.UploadEvaluationAudioResponse() + client.upload_evaluation_audio(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.UploadEvaluationAudioRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_evaluation_empty_call_grpc(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation), "__call__" + ) as call: + call.return_value = gcc_evaluation.Evaluation() + client.create_evaluation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.CreateEvaluationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_generate_evaluation_empty_call_grpc(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_evaluation), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.generate_evaluation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.GenerateEvaluationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_evaluations_empty_call_grpc(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_evaluations), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.import_evaluations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.ImportEvaluationsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_evaluation_dataset_empty_call_grpc(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation_dataset), "__call__" + ) as call: + call.return_value = evaluation.EvaluationDataset() + client.create_evaluation_dataset(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.CreateEvaluationDatasetRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_evaluation_empty_call_grpc(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_evaluation), "__call__" + ) as call: + call.return_value = gcc_evaluation.Evaluation() + client.update_evaluation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.UpdateEvaluationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_evaluation_dataset_empty_call_grpc(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_evaluation_dataset), "__call__" + ) as call: + call.return_value = evaluation.EvaluationDataset() + client.update_evaluation_dataset(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.UpdateEvaluationDatasetRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_evaluation_empty_call_grpc(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation), "__call__" + ) as call: + call.return_value = None + client.delete_evaluation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.DeleteEvaluationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_evaluation_result_empty_call_grpc(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_result), "__call__" + ) as call: + call.return_value = None + client.delete_evaluation_result(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.DeleteEvaluationResultRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_evaluation_dataset_empty_call_grpc(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_dataset), "__call__" + ) as call: + call.return_value = None + client.delete_evaluation_dataset(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.DeleteEvaluationDatasetRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_evaluation_run_empty_call_grpc(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_run), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_evaluation_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.DeleteEvaluationRunRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_evaluation_empty_call_grpc(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_evaluation), "__call__") as call: + call.return_value = evaluation.Evaluation() + client.get_evaluation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.GetEvaluationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_evaluation_result_empty_call_grpc(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_evaluation_result), "__call__" + ) as call: + call.return_value = evaluation.EvaluationResult() + client.get_evaluation_result(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.GetEvaluationResultRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_evaluation_dataset_empty_call_grpc(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_evaluation_dataset), "__call__" + ) as call: + call.return_value = evaluation.EvaluationDataset() + client.get_evaluation_dataset(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.GetEvaluationDatasetRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_evaluation_run_empty_call_grpc(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_evaluation_run), "__call__" + ) as call: + call.return_value = evaluation.EvaluationRun() + client.get_evaluation_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.GetEvaluationRunRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_evaluations_empty_call_grpc(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_evaluations), "__call__") as call: + call.return_value = evaluation_service.ListEvaluationsResponse() + client.list_evaluations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.ListEvaluationsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_evaluation_results_empty_call_grpc(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_results), "__call__" + ) as call: + call.return_value = evaluation_service.ListEvaluationResultsResponse() + client.list_evaluation_results(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.ListEvaluationResultsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_evaluation_datasets_empty_call_grpc(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_datasets), "__call__" + ) as call: + call.return_value = evaluation_service.ListEvaluationDatasetsResponse() + client.list_evaluation_datasets(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.ListEvaluationDatasetsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_evaluation_runs_empty_call_grpc(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_runs), "__call__" + ) as call: + call.return_value = evaluation_service.ListEvaluationRunsResponse() + client.list_evaluation_runs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.ListEvaluationRunsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_evaluation_expectations_empty_call_grpc(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_expectations), "__call__" + ) as call: + call.return_value = evaluation_service.ListEvaluationExpectationsResponse() + client.list_evaluation_expectations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.ListEvaluationExpectationsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_evaluation_expectation_empty_call_grpc(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_evaluation_expectation), "__call__" + ) as call: + call.return_value = evaluation.EvaluationExpectation() + client.get_evaluation_expectation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.GetEvaluationExpectationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_evaluation_expectation_empty_call_grpc(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation_expectation), "__call__" + ) as call: + call.return_value = evaluation.EvaluationExpectation() + client.create_evaluation_expectation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.CreateEvaluationExpectationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_evaluation_expectation_empty_call_grpc(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_evaluation_expectation), "__call__" + ) as call: + call.return_value = evaluation.EvaluationExpectation() + client.update_evaluation_expectation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.UpdateEvaluationExpectationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_evaluation_expectation_empty_call_grpc(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_expectation), "__call__" + ) as call: + call.return_value = None + client.delete_evaluation_expectation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.DeleteEvaluationExpectationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_scheduled_evaluation_run_empty_call_grpc(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_scheduled_evaluation_run), "__call__" + ) as call: + call.return_value = evaluation.ScheduledEvaluationRun() + client.create_scheduled_evaluation_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.CreateScheduledEvaluationRunRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_scheduled_evaluation_run_empty_call_grpc(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_scheduled_evaluation_run), "__call__" + ) as call: + call.return_value = evaluation.ScheduledEvaluationRun() + client.get_scheduled_evaluation_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.GetScheduledEvaluationRunRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_scheduled_evaluation_runs_empty_call_grpc(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_scheduled_evaluation_runs), "__call__" + ) as call: + call.return_value = evaluation_service.ListScheduledEvaluationRunsResponse() + client.list_scheduled_evaluation_runs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.ListScheduledEvaluationRunsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_scheduled_evaluation_run_empty_call_grpc(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_scheduled_evaluation_run), "__call__" + ) as call: + call.return_value = evaluation.ScheduledEvaluationRun() + client.update_scheduled_evaluation_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.UpdateScheduledEvaluationRunRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_scheduled_evaluation_run_empty_call_grpc(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_scheduled_evaluation_run), "__call__" + ) as call: + call.return_value = None + client.delete_scheduled_evaluation_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.DeleteScheduledEvaluationRunRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_test_persona_voice_empty_call_grpc(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.test_persona_voice), "__call__" + ) as call: + call.return_value = evaluation_service.TestPersonaVoiceResponse() + client.test_persona_voice(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.TestPersonaVoiceRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = EvaluationServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_run_evaluation_empty_call_grpc_asyncio(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.run_evaluation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.run_evaluation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation.RunEvaluationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_upload_evaluation_audio_empty_call_grpc_asyncio(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.upload_evaluation_audio), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.UploadEvaluationAudioResponse( + audio_gcs_uri="audio_gcs_uri_value", + audio_transcript="audio_transcript_value", + ) + ) + await client.upload_evaluation_audio(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.UploadEvaluationAudioRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_evaluation_empty_call_grpc_asyncio(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_evaluation.Evaluation( + name="name_value", + display_name="display_name_value", + description="description_value", + tags=["tags_value"], + evaluation_datasets=["evaluation_datasets_value"], + created_by="created_by_value", + last_updated_by="last_updated_by_value", + evaluation_runs=["evaluation_runs_value"], + etag="etag_value", + invalid=True, + ) + ) + await client.create_evaluation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.CreateEvaluationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_generate_evaluation_empty_call_grpc_asyncio(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_evaluation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.generate_evaluation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.GenerateEvaluationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_import_evaluations_empty_call_grpc_asyncio(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_evaluations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.import_evaluations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.ImportEvaluationsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_evaluation_dataset_empty_call_grpc_asyncio(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation_dataset), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.EvaluationDataset( + name="name_value", + display_name="display_name_value", + evaluations=["evaluations_value"], + etag="etag_value", + created_by="created_by_value", + last_updated_by="last_updated_by_value", + ) + ) + await client.create_evaluation_dataset(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.CreateEvaluationDatasetRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_evaluation_empty_call_grpc_asyncio(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_evaluation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcc_evaluation.Evaluation( + name="name_value", + display_name="display_name_value", + description="description_value", + tags=["tags_value"], + evaluation_datasets=["evaluation_datasets_value"], + created_by="created_by_value", + last_updated_by="last_updated_by_value", + evaluation_runs=["evaluation_runs_value"], + etag="etag_value", + invalid=True, + ) + ) + await client.update_evaluation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.UpdateEvaluationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_evaluation_dataset_empty_call_grpc_asyncio(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_evaluation_dataset), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.EvaluationDataset( + name="name_value", + display_name="display_name_value", + evaluations=["evaluations_value"], + etag="etag_value", + created_by="created_by_value", + last_updated_by="last_updated_by_value", + ) + ) + await client.update_evaluation_dataset(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.UpdateEvaluationDatasetRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_evaluation_empty_call_grpc_asyncio(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_evaluation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.DeleteEvaluationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_evaluation_result_empty_call_grpc_asyncio(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_result), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_evaluation_result(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.DeleteEvaluationResultRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_evaluation_dataset_empty_call_grpc_asyncio(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_dataset), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_evaluation_dataset(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.DeleteEvaluationDatasetRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_evaluation_run_empty_call_grpc_asyncio(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_run), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_evaluation_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.DeleteEvaluationRunRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_evaluation_empty_call_grpc_asyncio(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_evaluation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.Evaluation( + name="name_value", + display_name="display_name_value", + description="description_value", + tags=["tags_value"], + evaluation_datasets=["evaluation_datasets_value"], + created_by="created_by_value", + last_updated_by="last_updated_by_value", + evaluation_runs=["evaluation_runs_value"], + etag="etag_value", + invalid=True, + ) + ) + await client.get_evaluation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.GetEvaluationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_evaluation_result_empty_call_grpc_asyncio(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_evaluation_result), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.EvaluationResult( + name="name_value", + display_name="display_name_value", + evaluation_status=evaluation.EvaluationResult.Outcome.PASS, + evaluation_run="evaluation_run_value", + initiated_by="initiated_by_value", + app_version="app_version_value", + app_version_display_name="app_version_display_name_value", + changelog="changelog_value", + execution_state=evaluation.EvaluationResult.ExecutionState.RUNNING, + golden_run_method=golden_run.GoldenRunMethod.STABLE, + ) + ) + await client.get_evaluation_result(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.GetEvaluationResultRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_evaluation_dataset_empty_call_grpc_asyncio(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_evaluation_dataset), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.EvaluationDataset( + name="name_value", + display_name="display_name_value", + evaluations=["evaluations_value"], + etag="etag_value", + created_by="created_by_value", + last_updated_by="last_updated_by_value", + ) + ) + await client.get_evaluation_dataset(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.GetEvaluationDatasetRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_evaluation_run_empty_call_grpc_asyncio(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_evaluation_run), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.EvaluationRun( + name="name_value", + display_name="display_name_value", + evaluation_results=["evaluation_results_value"], + initiated_by="initiated_by_value", + app_version="app_version_value", + app_version_display_name="app_version_display_name_value", + changelog="changelog_value", + evaluations=["evaluations_value"], + evaluation_dataset="evaluation_dataset_value", + evaluation_type=evaluation.EvaluationRun.EvaluationType.GOLDEN, + state=evaluation.EvaluationRun.EvaluationRunState.RUNNING, + run_count=989, + scheduled_evaluation_run="scheduled_evaluation_run_value", + golden_run_method=golden_run.GoldenRunMethod.STABLE, + ) + ) + await client.get_evaluation_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.GetEvaluationRunRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_evaluations_empty_call_grpc_asyncio(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_evaluations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.ListEvaluationsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_evaluations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.ListEvaluationsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_evaluation_results_empty_call_grpc_asyncio(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_results), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.ListEvaluationResultsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_evaluation_results(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.ListEvaluationResultsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_evaluation_datasets_empty_call_grpc_asyncio(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_datasets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.ListEvaluationDatasetsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_evaluation_datasets(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.ListEvaluationDatasetsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_evaluation_runs_empty_call_grpc_asyncio(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_runs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.ListEvaluationRunsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_evaluation_runs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.ListEvaluationRunsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_evaluation_expectations_empty_call_grpc_asyncio(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_expectations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.ListEvaluationExpectationsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_evaluation_expectations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.ListEvaluationExpectationsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_evaluation_expectation_empty_call_grpc_asyncio(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_evaluation_expectation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.EvaluationExpectation( + name="name_value", + display_name="display_name_value", + tags=["tags_value"], + etag="etag_value", + ) + ) + await client.get_evaluation_expectation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.GetEvaluationExpectationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_evaluation_expectation_empty_call_grpc_asyncio(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation_expectation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.EvaluationExpectation( + name="name_value", + display_name="display_name_value", + tags=["tags_value"], + etag="etag_value", + ) + ) + await client.create_evaluation_expectation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.CreateEvaluationExpectationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_evaluation_expectation_empty_call_grpc_asyncio(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_evaluation_expectation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.EvaluationExpectation( + name="name_value", + display_name="display_name_value", + tags=["tags_value"], + etag="etag_value", + ) + ) + await client.update_evaluation_expectation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.UpdateEvaluationExpectationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_evaluation_expectation_empty_call_grpc_asyncio(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_expectation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_evaluation_expectation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.DeleteEvaluationExpectationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_scheduled_evaluation_run_empty_call_grpc_asyncio(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_scheduled_evaluation_run), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.ScheduledEvaluationRun( + name="name_value", + display_name="display_name_value", + description="description_value", + active=True, + last_completed_run="last_completed_run_value", + total_executions=1738, + created_by="created_by_value", + last_updated_by="last_updated_by_value", + etag="etag_value", + ) + ) + await client.create_scheduled_evaluation_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.CreateScheduledEvaluationRunRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_scheduled_evaluation_run_empty_call_grpc_asyncio(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_scheduled_evaluation_run), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.ScheduledEvaluationRun( + name="name_value", + display_name="display_name_value", + description="description_value", + active=True, + last_completed_run="last_completed_run_value", + total_executions=1738, + created_by="created_by_value", + last_updated_by="last_updated_by_value", + etag="etag_value", + ) + ) + await client.get_scheduled_evaluation_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.GetScheduledEvaluationRunRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_scheduled_evaluation_runs_empty_call_grpc_asyncio(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_scheduled_evaluation_runs), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.ListScheduledEvaluationRunsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_scheduled_evaluation_runs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.ListScheduledEvaluationRunsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_scheduled_evaluation_run_empty_call_grpc_asyncio(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_scheduled_evaluation_run), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.ScheduledEvaluationRun( + name="name_value", + display_name="display_name_value", + description="description_value", + active=True, + last_completed_run="last_completed_run_value", + total_executions=1738, + created_by="created_by_value", + last_updated_by="last_updated_by_value", + etag="etag_value", + ) + ) + await client.update_scheduled_evaluation_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.UpdateScheduledEvaluationRunRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_scheduled_evaluation_run_empty_call_grpc_asyncio(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_scheduled_evaluation_run), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_scheduled_evaluation_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.DeleteScheduledEvaluationRunRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_test_persona_voice_empty_call_grpc_asyncio(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.test_persona_voice), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation_service.TestPersonaVoiceResponse( + audio=b"audio_blob", + ) + ) + await client.test_persona_voice(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.TestPersonaVoiceRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = EvaluationServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_run_evaluation_rest_bad_request(request_type=evaluation.RunEvaluationRequest): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"app": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.run_evaluation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation.RunEvaluationRequest, + dict, + ], +) +def test_run_evaluation_rest_call_success(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"app": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.run_evaluation(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_run_evaluation_rest_interceptors(null_interceptor): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EvaluationServiceRestInterceptor(), + ) + client = EvaluationServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.EvaluationServiceRestInterceptor, "post_run_evaluation" + ) as post, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "post_run_evaluation_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "pre_run_evaluation" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = evaluation.RunEvaluationRequest.pb( + evaluation.RunEvaluationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = evaluation.RunEvaluationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.run_evaluation( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_upload_evaluation_audio_rest_bad_request( + request_type=evaluation_service.UploadEvaluationAudioRequest, +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"app": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.upload_evaluation_audio(request) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.UploadEvaluationAudioRequest, + dict, + ], +) +def test_upload_evaluation_audio_rest_call_success(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"app": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation_service.UploadEvaluationAudioResponse( + audio_gcs_uri="audio_gcs_uri_value", + audio_transcript="audio_transcript_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = evaluation_service.UploadEvaluationAudioResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.upload_evaluation_audio(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation_service.UploadEvaluationAudioResponse) + assert response.audio_gcs_uri == "audio_gcs_uri_value" + assert response.audio_transcript == "audio_transcript_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_upload_evaluation_audio_rest_interceptors(null_interceptor): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EvaluationServiceRestInterceptor(), + ) + client = EvaluationServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "post_upload_evaluation_audio" + ) as post, mock.patch.object( + transports.EvaluationServiceRestInterceptor, + "post_upload_evaluation_audio_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "pre_upload_evaluation_audio" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = evaluation_service.UploadEvaluationAudioRequest.pb( + evaluation_service.UploadEvaluationAudioRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = evaluation_service.UploadEvaluationAudioResponse.to_json( + evaluation_service.UploadEvaluationAudioResponse() + ) + req.return_value.content = return_value + + request = evaluation_service.UploadEvaluationAudioRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = evaluation_service.UploadEvaluationAudioResponse() + post_with_metadata.return_value = ( + evaluation_service.UploadEvaluationAudioResponse(), + metadata, + ) + + client.upload_evaluation_audio( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_evaluation_rest_bad_request( + request_type=evaluation_service.CreateEvaluationRequest, +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_evaluation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.CreateEvaluationRequest, + dict, + ], +) +def test_create_evaluation_rest_call_success(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request_init["evaluation"] = { + "golden": { + "turns": [ + { + "steps": [ + { + "user_input": { + "text": "text_value", + "dtmf": "dtmf_value", + "audio": b"audio_blob", + "tool_responses": { + "tool_responses": [ + { + "tool": "tool_value", + "toolset_tool": { + "toolset": "toolset_value", + "tool_id": "tool_id_value", + }, + "id": "id_value", + "display_name": "display_name_value", + "response": {"fields": {}}, + } + ] + }, + "image": { + "mime_type": "mime_type_value", + "data": b"data_blob", + }, + "blob": { + "mime_type": "mime_type_value", + "data": b"data_blob", + }, + "variables": {}, + "event": {"event": "event_value"}, + "will_continue": True, + }, + "agent_transfer": { + "target_agent": "target_agent_value", + "display_name": "display_name_value", + }, + "expectation": { + "tool_call": { + "tool": "tool_value", + "toolset_tool": {}, + "id": "id_value", + "display_name": "display_name_value", + "args": {}, + }, + "tool_response": {}, + "agent_response": { + "role": "role_value", + "chunks": [ + { + "text": "text_value", + "transcript": "transcript_value", + "blob": {}, + "payload": {}, + "image": {}, + "tool_call": {}, + "tool_response": {}, + "agent_transfer": {}, + "updated_variables": {}, + "default_variables": {}, + } + ], + "event_time": {"seconds": 751, "nanos": 543}, + }, + "agent_transfer": {}, + "updated_variables": {}, + "mock_tool_response": {}, + "note": "note_value", + }, + } + ], + "root_span": { + "name": "name_value", + "start_time": {}, + "end_time": {}, + "duration": {"seconds": 751, "nanos": 543}, + "attributes": {}, + "child_spans": {}, + }, + } + ], + "evaluation_expectations": [ + "evaluation_expectations_value1", + "evaluation_expectations_value2", + ], + }, + "scenario": { + "task": "task_value", + "user_facts": [{"name": "name_value", "value": "value_value"}], + "max_turns": 993, + "rubrics": ["rubrics_value1", "rubrics_value2"], + "scenario_expectations": [ + { + "tool_expectation": { + "expected_tool_call": {}, + "mock_tool_response": {}, + }, + "agent_response": {}, + } + ], + "variable_overrides": {}, + "task_completion_behavior": 1, + "user_goal_behavior": 1, + "evaluation_expectations": [ + "evaluation_expectations_value1", + "evaluation_expectations_value2", + ], + }, + "name": "name_value", + "display_name": "display_name_value", + "description": "description_value", + "tags": ["tags_value1", "tags_value2"], + "evaluation_datasets": [ + "evaluation_datasets_value1", + "evaluation_datasets_value2", + ], + "create_time": {}, + "created_by": "created_by_value", + "update_time": {}, + "last_updated_by": "last_updated_by_value", + "evaluation_runs": ["evaluation_runs_value1", "evaluation_runs_value2"], + "etag": "etag_value", + "aggregated_metrics": { + "metrics_by_app_version": [ + { + "app_version_id": "app_version_id_value", + "tool_metrics": [ + {"tool": "tool_value", "pass_count": 1087, "fail_count": 1060} + ], + "semantic_similarity_metrics": [{"score": 0.54}], + "hallucination_metrics": [{"score": 0.54}], + "tool_call_latency_metrics": [ + {"tool": "tool_value", "average_latency": {}} + ], + "turn_latency_metrics": [{"average_latency": {}}], + "pass_count": 1087, + "fail_count": 1060, + "metrics_by_turn": [ + { + "turn_index": 1088, + "tool_metrics": {}, + "semantic_similarity_metrics": {}, + "hallucination_metrics": {}, + "tool_call_latency_metrics": {}, + "turn_latency_metrics": {}, + } + ], + } + ] + }, + "last_completed_result": { + "golden_result": { + "turn_replay_results": [ + { + "conversation": "conversation_value", + "expectation_outcome": [ + { + "observed_tool_call": {}, + "observed_tool_response": {}, + "observed_agent_response": {}, + "observed_agent_transfer": {}, + "expectation": {}, + "outcome": 1, + "semantic_similarity_result": { + "score": 540, + "label": "label_value", + "explanation": "explanation_value", + "outcome": 1, + }, + "tool_invocation_result": { + "parameter_correctness_score": 0.2886, + "outcome": 1, + "explanation": "explanation_value", + }, + } + ], + "hallucination_result": { + "score": 540, + "label": "label_value", + "explanation": "explanation_value", + }, + "tool_invocation_score": 0.2258, + "tool_ordered_invocation_score": 0.3094, + "turn_latency": {}, + "tool_call_latencies": [ + { + "tool": "tool_value", + "display_name": "display_name_value", + "start_time": {}, + "end_time": {}, + "execution_latency": {}, + } + ], + "semantic_similarity_result": {}, + "overall_tool_invocation_result": { + "tool_invocation_score": 0.2258, + "outcome": 1, + }, + "error_info": { + "error_type": 1, + "error_message": "error_message_value", + "session_id": "session_id_value", + }, + "span_latencies": [ + { + "resource": "resource_value", + "toolset": {}, + "model": "model_value", + "callback": "callback_value", + "type_": 1, + "display_name": "display_name_value", + "start_time": {}, + "end_time": {}, + "execution_latency": {}, + } + ], + } + ], + "evaluation_expectation_results": [ + { + "evaluation_expectation": "evaluation_expectation_value", + "prompt": "prompt_value", + "outcome": 1, + "explanation": "explanation_value", + } + ], + }, + "scenario_result": { + "conversation": "conversation_value", + "task": "task_value", + "user_facts": {}, + "expectation_outcomes": [ + { + "observed_tool_call": {"tool_call": {}, "tool_response": {}}, + "observed_agent_response": {}, + "expectation": {}, + "outcome": 1, + } + ], + "rubric_outcomes": [ + { + "rubric": "rubric_value", + "score": 0.54, + "score_explanation": "score_explanation_value", + } + ], + "hallucination_result": {}, + "task_completion_result": { + "score": 540, + "label": "label_value", + "explanation": "explanation_value", + }, + "tool_call_latencies": {}, + "user_goal_satisfaction_result": { + "score": 540, + "label": "label_value", + "explanation": "explanation_value", + }, + "all_expectations_satisfied": True, + "task_completed": True, + "span_latencies": {}, + "evaluation_expectation_results": {}, + }, + "name": "name_value", + "display_name": "display_name_value", + "create_time": {}, + "evaluation_status": 1, + "evaluation_run": "evaluation_run_value", + "persona": { + "name": "name_value", + "description": "description_value", + "display_name": "display_name_value", + "personality": "personality_value", + "speech_config": { + "speaking_rate": 0.1373, + "environment": 3, + "voice_id": "voice_id_value", + }, + }, + "error_info": {}, + "error": { + "code": 411, + "message": "message_value", + "details": [ + { + "type_url": "type.googleapis.com/google.protobuf.Duration", + "value": b"\x08\x0c\x10\xdb\x07", + } + ], + }, + "initiated_by": "initiated_by_value", + "app_version": "app_version_value", + "app_version_display_name": "app_version_display_name_value", + "changelog": "changelog_value", + "changelog_create_time": {}, + "execution_state": 1, + "evaluation_metrics_thresholds": { + "golden_evaluation_metrics_thresholds": { + "turn_level_metrics_thresholds": { + "semantic_similarity_success_threshold": 3966, + "overall_tool_invocation_correctness_threshold": 0.4833, + "semantic_similarity_channel": 1, + }, + "expectation_level_metrics_thresholds": { + "tool_invocation_parameter_correctness_threshold": 0.5037 + }, + "tool_matching_settings": {"extra_tool_call_behavior": 1}, + }, + "hallucination_metric_behavior": 1, + "golden_hallucination_metric_behavior": 1, + "scenario_hallucination_metric_behavior": 1, + }, + "config": { + "input_audio_config": { + "audio_encoding": 1, + "sample_rate_hertz": 1817, + "noise_suppression_level": "noise_suppression_level_value", + }, + "output_audio_config": {"audio_encoding": 1, "sample_rate_hertz": 1817}, + "evaluation_channel": 1, + "tool_call_behaviour": 1, + }, + "golden_run_method": 1, + }, + "invalid": True, + "last_ten_results": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = evaluation_service.CreateEvaluationRequest.meta.fields["evaluation"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["evaluation"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["evaluation"][field])): + del request_init["evaluation"][field][i][subfield] + else: + del request_init["evaluation"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcc_evaluation.Evaluation( + name="name_value", + display_name="display_name_value", + description="description_value", + tags=["tags_value"], + evaluation_datasets=["evaluation_datasets_value"], + created_by="created_by_value", + last_updated_by="last_updated_by_value", + evaluation_runs=["evaluation_runs_value"], + etag="etag_value", + invalid=True, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcc_evaluation.Evaluation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_evaluation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_evaluation.Evaluation) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.tags == ["tags_value"] + assert response.evaluation_datasets == ["evaluation_datasets_value"] + assert response.created_by == "created_by_value" + assert response.last_updated_by == "last_updated_by_value" + assert response.evaluation_runs == ["evaluation_runs_value"] + assert response.etag == "etag_value" + assert response.invalid is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_evaluation_rest_interceptors(null_interceptor): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EvaluationServiceRestInterceptor(), + ) + client = EvaluationServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "post_create_evaluation" + ) as post, mock.patch.object( + transports.EvaluationServiceRestInterceptor, + "post_create_evaluation_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "pre_create_evaluation" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = evaluation_service.CreateEvaluationRequest.pb( + evaluation_service.CreateEvaluationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gcc_evaluation.Evaluation.to_json(gcc_evaluation.Evaluation()) + req.return_value.content = return_value + + request = evaluation_service.CreateEvaluationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcc_evaluation.Evaluation() + post_with_metadata.return_value = gcc_evaluation.Evaluation(), metadata + + client.create_evaluation( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_generate_evaluation_rest_bad_request( + request_type=evaluation_service.GenerateEvaluationRequest, +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "conversation": "projects/sample1/locations/sample2/apps/sample3/conversations/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.generate_evaluation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.GenerateEvaluationRequest, + dict, + ], +) +def test_generate_evaluation_rest_call_success(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "conversation": "projects/sample1/locations/sample2/apps/sample3/conversations/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.generate_evaluation(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_generate_evaluation_rest_interceptors(null_interceptor): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EvaluationServiceRestInterceptor(), + ) + client = EvaluationServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.EvaluationServiceRestInterceptor, "post_generate_evaluation" + ) as post, mock.patch.object( + transports.EvaluationServiceRestInterceptor, + "post_generate_evaluation_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "pre_generate_evaluation" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = evaluation_service.GenerateEvaluationRequest.pb( + evaluation_service.GenerateEvaluationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = evaluation_service.GenerateEvaluationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.generate_evaluation( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_import_evaluations_rest_bad_request( + request_type=evaluation_service.ImportEvaluationsRequest, +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.import_evaluations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.ImportEvaluationsRequest, + dict, + ], +) +def test_import_evaluations_rest_call_success(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.import_evaluations(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_import_evaluations_rest_interceptors(null_interceptor): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EvaluationServiceRestInterceptor(), + ) + client = EvaluationServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.EvaluationServiceRestInterceptor, "post_import_evaluations" + ) as post, mock.patch.object( + transports.EvaluationServiceRestInterceptor, + "post_import_evaluations_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "pre_import_evaluations" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = evaluation_service.ImportEvaluationsRequest.pb( + evaluation_service.ImportEvaluationsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = evaluation_service.ImportEvaluationsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.import_evaluations( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_evaluation_dataset_rest_bad_request( + request_type=evaluation_service.CreateEvaluationDatasetRequest, +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_evaluation_dataset(request) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.CreateEvaluationDatasetRequest, + dict, + ], +) +def test_create_evaluation_dataset_rest_call_success(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request_init["evaluation_dataset"] = { + "name": "name_value", + "display_name": "display_name_value", + "evaluations": ["evaluations_value1", "evaluations_value2"], + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "etag": "etag_value", + "created_by": "created_by_value", + "last_updated_by": "last_updated_by_value", + "aggregated_metrics": { + "metrics_by_app_version": [ + { + "app_version_id": "app_version_id_value", + "tool_metrics": [ + {"tool": "tool_value", "pass_count": 1087, "fail_count": 1060} + ], + "semantic_similarity_metrics": [{"score": 0.54}], + "hallucination_metrics": [{"score": 0.54}], + "tool_call_latency_metrics": [ + { + "tool": "tool_value", + "average_latency": {"seconds": 751, "nanos": 543}, + } + ], + "turn_latency_metrics": [{"average_latency": {}}], + "pass_count": 1087, + "fail_count": 1060, + "metrics_by_turn": [ + { + "turn_index": 1088, + "tool_metrics": {}, + "semantic_similarity_metrics": {}, + "hallucination_metrics": {}, + "tool_call_latency_metrics": {}, + "turn_latency_metrics": {}, + } + ], + } + ] + }, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = evaluation_service.CreateEvaluationDatasetRequest.meta.fields[ + "evaluation_dataset" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["evaluation_dataset"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["evaluation_dataset"][field])): + del request_init["evaluation_dataset"][field][i][subfield] + else: + del request_init["evaluation_dataset"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation.EvaluationDataset( + name="name_value", + display_name="display_name_value", + evaluations=["evaluations_value"], + etag="etag_value", + created_by="created_by_value", + last_updated_by="last_updated_by_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = evaluation.EvaluationDataset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_evaluation_dataset(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.EvaluationDataset) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.evaluations == ["evaluations_value"] + assert response.etag == "etag_value" + assert response.created_by == "created_by_value" + assert response.last_updated_by == "last_updated_by_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_evaluation_dataset_rest_interceptors(null_interceptor): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EvaluationServiceRestInterceptor(), + ) + client = EvaluationServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "post_create_evaluation_dataset" + ) as post, mock.patch.object( + transports.EvaluationServiceRestInterceptor, + "post_create_evaluation_dataset_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "pre_create_evaluation_dataset" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = evaluation_service.CreateEvaluationDatasetRequest.pb( + evaluation_service.CreateEvaluationDatasetRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = evaluation.EvaluationDataset.to_json( + evaluation.EvaluationDataset() + ) + req.return_value.content = return_value + + request = evaluation_service.CreateEvaluationDatasetRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = evaluation.EvaluationDataset() + post_with_metadata.return_value = evaluation.EvaluationDataset(), metadata + + client.create_evaluation_dataset( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_evaluation_rest_bad_request( + request_type=evaluation_service.UpdateEvaluationRequest, +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "evaluation": { + "name": "projects/sample1/locations/sample2/apps/sample3/evaluations/sample4" + } + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_evaluation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.UpdateEvaluationRequest, + dict, + ], +) +def test_update_evaluation_rest_call_success(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "evaluation": { + "name": "projects/sample1/locations/sample2/apps/sample3/evaluations/sample4" + } + } + request_init["evaluation"] = { + "golden": { + "turns": [ + { + "steps": [ + { + "user_input": { + "text": "text_value", + "dtmf": "dtmf_value", + "audio": b"audio_blob", + "tool_responses": { + "tool_responses": [ + { + "tool": "tool_value", + "toolset_tool": { + "toolset": "toolset_value", + "tool_id": "tool_id_value", + }, + "id": "id_value", + "display_name": "display_name_value", + "response": {"fields": {}}, + } + ] + }, + "image": { + "mime_type": "mime_type_value", + "data": b"data_blob", + }, + "blob": { + "mime_type": "mime_type_value", + "data": b"data_blob", + }, + "variables": {}, + "event": {"event": "event_value"}, + "will_continue": True, + }, + "agent_transfer": { + "target_agent": "target_agent_value", + "display_name": "display_name_value", + }, + "expectation": { + "tool_call": { + "tool": "tool_value", + "toolset_tool": {}, + "id": "id_value", + "display_name": "display_name_value", + "args": {}, + }, + "tool_response": {}, + "agent_response": { + "role": "role_value", + "chunks": [ + { + "text": "text_value", + "transcript": "transcript_value", + "blob": {}, + "payload": {}, + "image": {}, + "tool_call": {}, + "tool_response": {}, + "agent_transfer": {}, + "updated_variables": {}, + "default_variables": {}, + } + ], + "event_time": {"seconds": 751, "nanos": 543}, + }, + "agent_transfer": {}, + "updated_variables": {}, + "mock_tool_response": {}, + "note": "note_value", + }, + } + ], + "root_span": { + "name": "name_value", + "start_time": {}, + "end_time": {}, + "duration": {"seconds": 751, "nanos": 543}, + "attributes": {}, + "child_spans": {}, + }, + } + ], + "evaluation_expectations": [ + "evaluation_expectations_value1", + "evaluation_expectations_value2", + ], + }, + "scenario": { + "task": "task_value", + "user_facts": [{"name": "name_value", "value": "value_value"}], + "max_turns": 993, + "rubrics": ["rubrics_value1", "rubrics_value2"], + "scenario_expectations": [ + { + "tool_expectation": { + "expected_tool_call": {}, + "mock_tool_response": {}, + }, + "agent_response": {}, + } + ], + "variable_overrides": {}, + "task_completion_behavior": 1, + "user_goal_behavior": 1, + "evaluation_expectations": [ + "evaluation_expectations_value1", + "evaluation_expectations_value2", + ], + }, + "name": "projects/sample1/locations/sample2/apps/sample3/evaluations/sample4", + "display_name": "display_name_value", + "description": "description_value", + "tags": ["tags_value1", "tags_value2"], + "evaluation_datasets": [ + "evaluation_datasets_value1", + "evaluation_datasets_value2", + ], + "create_time": {}, + "created_by": "created_by_value", + "update_time": {}, + "last_updated_by": "last_updated_by_value", + "evaluation_runs": ["evaluation_runs_value1", "evaluation_runs_value2"], + "etag": "etag_value", + "aggregated_metrics": { + "metrics_by_app_version": [ + { + "app_version_id": "app_version_id_value", + "tool_metrics": [ + {"tool": "tool_value", "pass_count": 1087, "fail_count": 1060} + ], + "semantic_similarity_metrics": [{"score": 0.54}], + "hallucination_metrics": [{"score": 0.54}], + "tool_call_latency_metrics": [ + {"tool": "tool_value", "average_latency": {}} + ], + "turn_latency_metrics": [{"average_latency": {}}], + "pass_count": 1087, + "fail_count": 1060, + "metrics_by_turn": [ + { + "turn_index": 1088, + "tool_metrics": {}, + "semantic_similarity_metrics": {}, + "hallucination_metrics": {}, + "tool_call_latency_metrics": {}, + "turn_latency_metrics": {}, + } + ], + } + ] + }, + "last_completed_result": { + "golden_result": { + "turn_replay_results": [ + { + "conversation": "conversation_value", + "expectation_outcome": [ + { + "observed_tool_call": {}, + "observed_tool_response": {}, + "observed_agent_response": {}, + "observed_agent_transfer": {}, + "expectation": {}, + "outcome": 1, + "semantic_similarity_result": { + "score": 540, + "label": "label_value", + "explanation": "explanation_value", + "outcome": 1, + }, + "tool_invocation_result": { + "parameter_correctness_score": 0.2886, + "outcome": 1, + "explanation": "explanation_value", + }, + } + ], + "hallucination_result": { + "score": 540, + "label": "label_value", + "explanation": "explanation_value", + }, + "tool_invocation_score": 0.2258, + "tool_ordered_invocation_score": 0.3094, + "turn_latency": {}, + "tool_call_latencies": [ + { + "tool": "tool_value", + "display_name": "display_name_value", + "start_time": {}, + "end_time": {}, + "execution_latency": {}, + } + ], + "semantic_similarity_result": {}, + "overall_tool_invocation_result": { + "tool_invocation_score": 0.2258, + "outcome": 1, + }, + "error_info": { + "error_type": 1, + "error_message": "error_message_value", + "session_id": "session_id_value", + }, + "span_latencies": [ + { + "resource": "resource_value", + "toolset": {}, + "model": "model_value", + "callback": "callback_value", + "type_": 1, + "display_name": "display_name_value", + "start_time": {}, + "end_time": {}, + "execution_latency": {}, + } + ], + } + ], + "evaluation_expectation_results": [ + { + "evaluation_expectation": "evaluation_expectation_value", + "prompt": "prompt_value", + "outcome": 1, + "explanation": "explanation_value", + } + ], + }, + "scenario_result": { + "conversation": "conversation_value", + "task": "task_value", + "user_facts": {}, + "expectation_outcomes": [ + { + "observed_tool_call": {"tool_call": {}, "tool_response": {}}, + "observed_agent_response": {}, + "expectation": {}, + "outcome": 1, + } + ], + "rubric_outcomes": [ + { + "rubric": "rubric_value", + "score": 0.54, + "score_explanation": "score_explanation_value", + } + ], + "hallucination_result": {}, + "task_completion_result": { + "score": 540, + "label": "label_value", + "explanation": "explanation_value", + }, + "tool_call_latencies": {}, + "user_goal_satisfaction_result": { + "score": 540, + "label": "label_value", + "explanation": "explanation_value", + }, + "all_expectations_satisfied": True, + "task_completed": True, + "span_latencies": {}, + "evaluation_expectation_results": {}, + }, + "name": "name_value", + "display_name": "display_name_value", + "create_time": {}, + "evaluation_status": 1, + "evaluation_run": "evaluation_run_value", + "persona": { + "name": "name_value", + "description": "description_value", + "display_name": "display_name_value", + "personality": "personality_value", + "speech_config": { + "speaking_rate": 0.1373, + "environment": 3, + "voice_id": "voice_id_value", + }, + }, + "error_info": {}, + "error": { + "code": 411, + "message": "message_value", + "details": [ + { + "type_url": "type.googleapis.com/google.protobuf.Duration", + "value": b"\x08\x0c\x10\xdb\x07", + } + ], + }, + "initiated_by": "initiated_by_value", + "app_version": "app_version_value", + "app_version_display_name": "app_version_display_name_value", + "changelog": "changelog_value", + "changelog_create_time": {}, + "execution_state": 1, + "evaluation_metrics_thresholds": { + "golden_evaluation_metrics_thresholds": { + "turn_level_metrics_thresholds": { + "semantic_similarity_success_threshold": 3966, + "overall_tool_invocation_correctness_threshold": 0.4833, + "semantic_similarity_channel": 1, + }, + "expectation_level_metrics_thresholds": { + "tool_invocation_parameter_correctness_threshold": 0.5037 + }, + "tool_matching_settings": {"extra_tool_call_behavior": 1}, + }, + "hallucination_metric_behavior": 1, + "golden_hallucination_metric_behavior": 1, + "scenario_hallucination_metric_behavior": 1, + }, + "config": { + "input_audio_config": { + "audio_encoding": 1, + "sample_rate_hertz": 1817, + "noise_suppression_level": "noise_suppression_level_value", + }, + "output_audio_config": {"audio_encoding": 1, "sample_rate_hertz": 1817}, + "evaluation_channel": 1, + "tool_call_behaviour": 1, + }, + "golden_run_method": 1, + }, + "invalid": True, + "last_ten_results": {}, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = evaluation_service.UpdateEvaluationRequest.meta.fields["evaluation"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["evaluation"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["evaluation"][field])): + del request_init["evaluation"][field][i][subfield] + else: + del request_init["evaluation"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = gcc_evaluation.Evaluation( + name="name_value", + display_name="display_name_value", + description="description_value", + tags=["tags_value"], + evaluation_datasets=["evaluation_datasets_value"], + created_by="created_by_value", + last_updated_by="last_updated_by_value", + evaluation_runs=["evaluation_runs_value"], + etag="etag_value", + invalid=True, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = gcc_evaluation.Evaluation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_evaluation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcc_evaluation.Evaluation) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.tags == ["tags_value"] + assert response.evaluation_datasets == ["evaluation_datasets_value"] + assert response.created_by == "created_by_value" + assert response.last_updated_by == "last_updated_by_value" + assert response.evaluation_runs == ["evaluation_runs_value"] + assert response.etag == "etag_value" + assert response.invalid is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_evaluation_rest_interceptors(null_interceptor): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EvaluationServiceRestInterceptor(), + ) + client = EvaluationServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "post_update_evaluation" + ) as post, mock.patch.object( + transports.EvaluationServiceRestInterceptor, + "post_update_evaluation_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "pre_update_evaluation" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = evaluation_service.UpdateEvaluationRequest.pb( + evaluation_service.UpdateEvaluationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = gcc_evaluation.Evaluation.to_json(gcc_evaluation.Evaluation()) + req.return_value.content = return_value + + request = evaluation_service.UpdateEvaluationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcc_evaluation.Evaluation() + post_with_metadata.return_value = gcc_evaluation.Evaluation(), metadata + + client.update_evaluation( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_evaluation_dataset_rest_bad_request( + request_type=evaluation_service.UpdateEvaluationDatasetRequest, +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "evaluation_dataset": { + "name": "projects/sample1/locations/sample2/apps/sample3/evaluationDatasets/sample4" + } + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_evaluation_dataset(request) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.UpdateEvaluationDatasetRequest, + dict, + ], +) +def test_update_evaluation_dataset_rest_call_success(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "evaluation_dataset": { + "name": "projects/sample1/locations/sample2/apps/sample3/evaluationDatasets/sample4" + } + } + request_init["evaluation_dataset"] = { + "name": "projects/sample1/locations/sample2/apps/sample3/evaluationDatasets/sample4", + "display_name": "display_name_value", + "evaluations": ["evaluations_value1", "evaluations_value2"], + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "etag": "etag_value", + "created_by": "created_by_value", + "last_updated_by": "last_updated_by_value", + "aggregated_metrics": { + "metrics_by_app_version": [ + { + "app_version_id": "app_version_id_value", + "tool_metrics": [ + {"tool": "tool_value", "pass_count": 1087, "fail_count": 1060} + ], + "semantic_similarity_metrics": [{"score": 0.54}], + "hallucination_metrics": [{"score": 0.54}], + "tool_call_latency_metrics": [ + { + "tool": "tool_value", + "average_latency": {"seconds": 751, "nanos": 543}, + } + ], + "turn_latency_metrics": [{"average_latency": {}}], + "pass_count": 1087, + "fail_count": 1060, + "metrics_by_turn": [ + { + "turn_index": 1088, + "tool_metrics": {}, + "semantic_similarity_metrics": {}, + "hallucination_metrics": {}, + "tool_call_latency_metrics": {}, + "turn_latency_metrics": {}, + } + ], + } + ] + }, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = evaluation_service.UpdateEvaluationDatasetRequest.meta.fields[ + "evaluation_dataset" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["evaluation_dataset"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["evaluation_dataset"][field])): + del request_init["evaluation_dataset"][field][i][subfield] + else: + del request_init["evaluation_dataset"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation.EvaluationDataset( + name="name_value", + display_name="display_name_value", + evaluations=["evaluations_value"], + etag="etag_value", + created_by="created_by_value", + last_updated_by="last_updated_by_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = evaluation.EvaluationDataset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_evaluation_dataset(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.EvaluationDataset) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.evaluations == ["evaluations_value"] + assert response.etag == "etag_value" + assert response.created_by == "created_by_value" + assert response.last_updated_by == "last_updated_by_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_evaluation_dataset_rest_interceptors(null_interceptor): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EvaluationServiceRestInterceptor(), + ) + client = EvaluationServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "post_update_evaluation_dataset" + ) as post, mock.patch.object( + transports.EvaluationServiceRestInterceptor, + "post_update_evaluation_dataset_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "pre_update_evaluation_dataset" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = evaluation_service.UpdateEvaluationDatasetRequest.pb( + evaluation_service.UpdateEvaluationDatasetRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = evaluation.EvaluationDataset.to_json( + evaluation.EvaluationDataset() + ) + req.return_value.content = return_value + + request = evaluation_service.UpdateEvaluationDatasetRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = evaluation.EvaluationDataset() + post_with_metadata.return_value = evaluation.EvaluationDataset(), metadata + + client.update_evaluation_dataset( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_evaluation_rest_bad_request( + request_type=evaluation_service.DeleteEvaluationRequest, +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/evaluations/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_evaluation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.DeleteEvaluationRequest, + dict, + ], +) +def test_delete_evaluation_rest_call_success(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/evaluations/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_evaluation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_evaluation_rest_interceptors(null_interceptor): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EvaluationServiceRestInterceptor(), + ) + client = EvaluationServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "pre_delete_evaluation" + ) as pre: + pre.assert_not_called() + pb_message = evaluation_service.DeleteEvaluationRequest.pb( + evaluation_service.DeleteEvaluationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = evaluation_service.DeleteEvaluationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_evaluation( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_delete_evaluation_result_rest_bad_request( + request_type=evaluation_service.DeleteEvaluationResultRequest, +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/evaluations/sample4/results/sample5" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_evaluation_result(request) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.DeleteEvaluationResultRequest, + dict, + ], +) +def test_delete_evaluation_result_rest_call_success(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/evaluations/sample4/results/sample5" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_evaluation_result(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_evaluation_result_rest_interceptors(null_interceptor): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EvaluationServiceRestInterceptor(), + ) + client = EvaluationServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "pre_delete_evaluation_result" + ) as pre: + pre.assert_not_called() + pb_message = evaluation_service.DeleteEvaluationResultRequest.pb( + evaluation_service.DeleteEvaluationResultRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = evaluation_service.DeleteEvaluationResultRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_evaluation_result( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_delete_evaluation_dataset_rest_bad_request( + request_type=evaluation_service.DeleteEvaluationDatasetRequest, +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/evaluationDatasets/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_evaluation_dataset(request) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.DeleteEvaluationDatasetRequest, + dict, + ], +) +def test_delete_evaluation_dataset_rest_call_success(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/evaluationDatasets/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_evaluation_dataset(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_evaluation_dataset_rest_interceptors(null_interceptor): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EvaluationServiceRestInterceptor(), + ) + client = EvaluationServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "pre_delete_evaluation_dataset" + ) as pre: + pre.assert_not_called() + pb_message = evaluation_service.DeleteEvaluationDatasetRequest.pb( + evaluation_service.DeleteEvaluationDatasetRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = evaluation_service.DeleteEvaluationDatasetRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_evaluation_dataset( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_delete_evaluation_run_rest_bad_request( + request_type=evaluation_service.DeleteEvaluationRunRequest, +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/evaluationRuns/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_evaluation_run(request) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.DeleteEvaluationRunRequest, + dict, + ], +) +def test_delete_evaluation_run_rest_call_success(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/evaluationRuns/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_evaluation_run(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_evaluation_run_rest_interceptors(null_interceptor): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EvaluationServiceRestInterceptor(), + ) + client = EvaluationServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.EvaluationServiceRestInterceptor, "post_delete_evaluation_run" + ) as post, mock.patch.object( + transports.EvaluationServiceRestInterceptor, + "post_delete_evaluation_run_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "pre_delete_evaluation_run" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = evaluation_service.DeleteEvaluationRunRequest.pb( + evaluation_service.DeleteEvaluationRunRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = evaluation_service.DeleteEvaluationRunRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_evaluation_run( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_evaluation_rest_bad_request( + request_type=evaluation_service.GetEvaluationRequest, +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/evaluations/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_evaluation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.GetEvaluationRequest, + dict, + ], +) +def test_get_evaluation_rest_call_success(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/evaluations/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation.Evaluation( + name="name_value", + display_name="display_name_value", + description="description_value", + tags=["tags_value"], + evaluation_datasets=["evaluation_datasets_value"], + created_by="created_by_value", + last_updated_by="last_updated_by_value", + evaluation_runs=["evaluation_runs_value"], + etag="etag_value", + invalid=True, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = evaluation.Evaluation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_evaluation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.Evaluation) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.tags == ["tags_value"] + assert response.evaluation_datasets == ["evaluation_datasets_value"] + assert response.created_by == "created_by_value" + assert response.last_updated_by == "last_updated_by_value" + assert response.evaluation_runs == ["evaluation_runs_value"] + assert response.etag == "etag_value" + assert response.invalid is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_evaluation_rest_interceptors(null_interceptor): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EvaluationServiceRestInterceptor(), + ) + client = EvaluationServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "post_get_evaluation" + ) as post, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "post_get_evaluation_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "pre_get_evaluation" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = evaluation_service.GetEvaluationRequest.pb( + evaluation_service.GetEvaluationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = evaluation.Evaluation.to_json(evaluation.Evaluation()) + req.return_value.content = return_value + + request = evaluation_service.GetEvaluationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = evaluation.Evaluation() + post_with_metadata.return_value = evaluation.Evaluation(), metadata + + client.get_evaluation( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_evaluation_result_rest_bad_request( + request_type=evaluation_service.GetEvaluationResultRequest, +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/evaluations/sample4/results/sample5" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_evaluation_result(request) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.GetEvaluationResultRequest, + dict, + ], +) +def test_get_evaluation_result_rest_call_success(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/evaluations/sample4/results/sample5" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation.EvaluationResult( + name="name_value", + display_name="display_name_value", + evaluation_status=evaluation.EvaluationResult.Outcome.PASS, + evaluation_run="evaluation_run_value", + initiated_by="initiated_by_value", + app_version="app_version_value", + app_version_display_name="app_version_display_name_value", + changelog="changelog_value", + execution_state=evaluation.EvaluationResult.ExecutionState.RUNNING, + golden_run_method=golden_run.GoldenRunMethod.STABLE, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = evaluation.EvaluationResult.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_evaluation_result(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.EvaluationResult) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.evaluation_status == evaluation.EvaluationResult.Outcome.PASS + assert response.evaluation_run == "evaluation_run_value" + assert response.initiated_by == "initiated_by_value" + assert response.app_version == "app_version_value" + assert response.app_version_display_name == "app_version_display_name_value" + assert response.changelog == "changelog_value" + assert ( + response.execution_state == evaluation.EvaluationResult.ExecutionState.RUNNING + ) + assert response.golden_run_method == golden_run.GoldenRunMethod.STABLE + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_evaluation_result_rest_interceptors(null_interceptor): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EvaluationServiceRestInterceptor(), + ) + client = EvaluationServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "post_get_evaluation_result" + ) as post, mock.patch.object( + transports.EvaluationServiceRestInterceptor, + "post_get_evaluation_result_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "pre_get_evaluation_result" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = evaluation_service.GetEvaluationResultRequest.pb( + evaluation_service.GetEvaluationResultRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = evaluation.EvaluationResult.to_json( + evaluation.EvaluationResult() + ) + req.return_value.content = return_value + + request = evaluation_service.GetEvaluationResultRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = evaluation.EvaluationResult() + post_with_metadata.return_value = evaluation.EvaluationResult(), metadata + + client.get_evaluation_result( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_evaluation_dataset_rest_bad_request( + request_type=evaluation_service.GetEvaluationDatasetRequest, +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/evaluationDatasets/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_evaluation_dataset(request) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.GetEvaluationDatasetRequest, + dict, + ], +) +def test_get_evaluation_dataset_rest_call_success(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/evaluationDatasets/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation.EvaluationDataset( + name="name_value", + display_name="display_name_value", + evaluations=["evaluations_value"], + etag="etag_value", + created_by="created_by_value", + last_updated_by="last_updated_by_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = evaluation.EvaluationDataset.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_evaluation_dataset(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.EvaluationDataset) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.evaluations == ["evaluations_value"] + assert response.etag == "etag_value" + assert response.created_by == "created_by_value" + assert response.last_updated_by == "last_updated_by_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_evaluation_dataset_rest_interceptors(null_interceptor): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EvaluationServiceRestInterceptor(), + ) + client = EvaluationServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "post_get_evaluation_dataset" + ) as post, mock.patch.object( + transports.EvaluationServiceRestInterceptor, + "post_get_evaluation_dataset_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "pre_get_evaluation_dataset" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = evaluation_service.GetEvaluationDatasetRequest.pb( + evaluation_service.GetEvaluationDatasetRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = evaluation.EvaluationDataset.to_json( + evaluation.EvaluationDataset() + ) + req.return_value.content = return_value + + request = evaluation_service.GetEvaluationDatasetRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = evaluation.EvaluationDataset() + post_with_metadata.return_value = evaluation.EvaluationDataset(), metadata + + client.get_evaluation_dataset( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_evaluation_run_rest_bad_request( + request_type=evaluation_service.GetEvaluationRunRequest, +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/evaluationRuns/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_evaluation_run(request) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.GetEvaluationRunRequest, + dict, + ], +) +def test_get_evaluation_run_rest_call_success(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/evaluationRuns/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation.EvaluationRun( + name="name_value", + display_name="display_name_value", + evaluation_results=["evaluation_results_value"], + initiated_by="initiated_by_value", + app_version="app_version_value", + app_version_display_name="app_version_display_name_value", + changelog="changelog_value", + evaluations=["evaluations_value"], + evaluation_dataset="evaluation_dataset_value", + evaluation_type=evaluation.EvaluationRun.EvaluationType.GOLDEN, + state=evaluation.EvaluationRun.EvaluationRunState.RUNNING, + run_count=989, + scheduled_evaluation_run="scheduled_evaluation_run_value", + golden_run_method=golden_run.GoldenRunMethod.STABLE, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = evaluation.EvaluationRun.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_evaluation_run(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.EvaluationRun) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.evaluation_results == ["evaluation_results_value"] + assert response.initiated_by == "initiated_by_value" + assert response.app_version == "app_version_value" + assert response.app_version_display_name == "app_version_display_name_value" + assert response.changelog == "changelog_value" + assert response.evaluations == ["evaluations_value"] + assert response.evaluation_dataset == "evaluation_dataset_value" + assert response.evaluation_type == evaluation.EvaluationRun.EvaluationType.GOLDEN + assert response.state == evaluation.EvaluationRun.EvaluationRunState.RUNNING + assert response.run_count == 989 + assert response.scheduled_evaluation_run == "scheduled_evaluation_run_value" + assert response.golden_run_method == golden_run.GoldenRunMethod.STABLE + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_evaluation_run_rest_interceptors(null_interceptor): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EvaluationServiceRestInterceptor(), + ) + client = EvaluationServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "post_get_evaluation_run" + ) as post, mock.patch.object( + transports.EvaluationServiceRestInterceptor, + "post_get_evaluation_run_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "pre_get_evaluation_run" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = evaluation_service.GetEvaluationRunRequest.pb( + evaluation_service.GetEvaluationRunRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = evaluation.EvaluationRun.to_json(evaluation.EvaluationRun()) + req.return_value.content = return_value + + request = evaluation_service.GetEvaluationRunRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = evaluation.EvaluationRun() + post_with_metadata.return_value = evaluation.EvaluationRun(), metadata + + client.get_evaluation_run( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_evaluations_rest_bad_request( + request_type=evaluation_service.ListEvaluationsRequest, +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_evaluations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.ListEvaluationsRequest, + dict, + ], +) +def test_list_evaluations_rest_call_success(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation_service.ListEvaluationsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = evaluation_service.ListEvaluationsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_evaluations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEvaluationsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_evaluations_rest_interceptors(null_interceptor): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EvaluationServiceRestInterceptor(), + ) + client = EvaluationServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "post_list_evaluations" + ) as post, mock.patch.object( + transports.EvaluationServiceRestInterceptor, + "post_list_evaluations_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "pre_list_evaluations" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = evaluation_service.ListEvaluationsRequest.pb( + evaluation_service.ListEvaluationsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = evaluation_service.ListEvaluationsResponse.to_json( + evaluation_service.ListEvaluationsResponse() + ) + req.return_value.content = return_value + + request = evaluation_service.ListEvaluationsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = evaluation_service.ListEvaluationsResponse() + post_with_metadata.return_value = ( + evaluation_service.ListEvaluationsResponse(), + metadata, + ) + + client.list_evaluations( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_evaluation_results_rest_bad_request( + request_type=evaluation_service.ListEvaluationResultsRequest, +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/apps/sample3/evaluations/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_evaluation_results(request) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.ListEvaluationResultsRequest, + dict, + ], +) +def test_list_evaluation_results_rest_call_success(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/apps/sample3/evaluations/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation_service.ListEvaluationResultsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = evaluation_service.ListEvaluationResultsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_evaluation_results(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEvaluationResultsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_evaluation_results_rest_interceptors(null_interceptor): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EvaluationServiceRestInterceptor(), + ) + client = EvaluationServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "post_list_evaluation_results" + ) as post, mock.patch.object( + transports.EvaluationServiceRestInterceptor, + "post_list_evaluation_results_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "pre_list_evaluation_results" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = evaluation_service.ListEvaluationResultsRequest.pb( + evaluation_service.ListEvaluationResultsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = evaluation_service.ListEvaluationResultsResponse.to_json( + evaluation_service.ListEvaluationResultsResponse() + ) + req.return_value.content = return_value + + request = evaluation_service.ListEvaluationResultsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = evaluation_service.ListEvaluationResultsResponse() + post_with_metadata.return_value = ( + evaluation_service.ListEvaluationResultsResponse(), + metadata, + ) + + client.list_evaluation_results( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_evaluation_datasets_rest_bad_request( + request_type=evaluation_service.ListEvaluationDatasetsRequest, +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_evaluation_datasets(request) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.ListEvaluationDatasetsRequest, + dict, + ], +) +def test_list_evaluation_datasets_rest_call_success(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation_service.ListEvaluationDatasetsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = evaluation_service.ListEvaluationDatasetsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_evaluation_datasets(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEvaluationDatasetsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_evaluation_datasets_rest_interceptors(null_interceptor): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EvaluationServiceRestInterceptor(), + ) + client = EvaluationServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "post_list_evaluation_datasets" + ) as post, mock.patch.object( + transports.EvaluationServiceRestInterceptor, + "post_list_evaluation_datasets_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "pre_list_evaluation_datasets" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = evaluation_service.ListEvaluationDatasetsRequest.pb( + evaluation_service.ListEvaluationDatasetsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = evaluation_service.ListEvaluationDatasetsResponse.to_json( + evaluation_service.ListEvaluationDatasetsResponse() + ) + req.return_value.content = return_value + + request = evaluation_service.ListEvaluationDatasetsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = evaluation_service.ListEvaluationDatasetsResponse() + post_with_metadata.return_value = ( + evaluation_service.ListEvaluationDatasetsResponse(), + metadata, + ) + + client.list_evaluation_datasets( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_evaluation_runs_rest_bad_request( + request_type=evaluation_service.ListEvaluationRunsRequest, +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_evaluation_runs(request) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.ListEvaluationRunsRequest, + dict, + ], +) +def test_list_evaluation_runs_rest_call_success(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation_service.ListEvaluationRunsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = evaluation_service.ListEvaluationRunsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_evaluation_runs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEvaluationRunsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_evaluation_runs_rest_interceptors(null_interceptor): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EvaluationServiceRestInterceptor(), + ) + client = EvaluationServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "post_list_evaluation_runs" + ) as post, mock.patch.object( + transports.EvaluationServiceRestInterceptor, + "post_list_evaluation_runs_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "pre_list_evaluation_runs" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = evaluation_service.ListEvaluationRunsRequest.pb( + evaluation_service.ListEvaluationRunsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = evaluation_service.ListEvaluationRunsResponse.to_json( + evaluation_service.ListEvaluationRunsResponse() + ) + req.return_value.content = return_value + + request = evaluation_service.ListEvaluationRunsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = evaluation_service.ListEvaluationRunsResponse() + post_with_metadata.return_value = ( + evaluation_service.ListEvaluationRunsResponse(), + metadata, + ) + + client.list_evaluation_runs( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_evaluation_expectations_rest_bad_request( + request_type=evaluation_service.ListEvaluationExpectationsRequest, +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_evaluation_expectations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.ListEvaluationExpectationsRequest, + dict, + ], +) +def test_list_evaluation_expectations_rest_call_success(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation_service.ListEvaluationExpectationsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = evaluation_service.ListEvaluationExpectationsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_evaluation_expectations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEvaluationExpectationsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_evaluation_expectations_rest_interceptors(null_interceptor): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EvaluationServiceRestInterceptor(), + ) + client = EvaluationServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "post_list_evaluation_expectations" + ) as post, mock.patch.object( + transports.EvaluationServiceRestInterceptor, + "post_list_evaluation_expectations_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "pre_list_evaluation_expectations" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = evaluation_service.ListEvaluationExpectationsRequest.pb( + evaluation_service.ListEvaluationExpectationsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = evaluation_service.ListEvaluationExpectationsResponse.to_json( + evaluation_service.ListEvaluationExpectationsResponse() + ) + req.return_value.content = return_value + + request = evaluation_service.ListEvaluationExpectationsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = evaluation_service.ListEvaluationExpectationsResponse() + post_with_metadata.return_value = ( + evaluation_service.ListEvaluationExpectationsResponse(), + metadata, + ) + + client.list_evaluation_expectations( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_evaluation_expectation_rest_bad_request( + request_type=evaluation_service.GetEvaluationExpectationRequest, +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/evaluationExpectations/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_evaluation_expectation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.GetEvaluationExpectationRequest, + dict, + ], +) +def test_get_evaluation_expectation_rest_call_success(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/evaluationExpectations/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation.EvaluationExpectation( + name="name_value", + display_name="display_name_value", + tags=["tags_value"], + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = evaluation.EvaluationExpectation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_evaluation_expectation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.EvaluationExpectation) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.tags == ["tags_value"] + assert response.etag == "etag_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_evaluation_expectation_rest_interceptors(null_interceptor): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EvaluationServiceRestInterceptor(), + ) + client = EvaluationServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "post_get_evaluation_expectation" + ) as post, mock.patch.object( + transports.EvaluationServiceRestInterceptor, + "post_get_evaluation_expectation_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "pre_get_evaluation_expectation" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = evaluation_service.GetEvaluationExpectationRequest.pb( + evaluation_service.GetEvaluationExpectationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = evaluation.EvaluationExpectation.to_json( + evaluation.EvaluationExpectation() + ) + req.return_value.content = return_value + + request = evaluation_service.GetEvaluationExpectationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = evaluation.EvaluationExpectation() + post_with_metadata.return_value = evaluation.EvaluationExpectation(), metadata + + client.get_evaluation_expectation( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_evaluation_expectation_rest_bad_request( + request_type=evaluation_service.CreateEvaluationExpectationRequest, +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_evaluation_expectation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.CreateEvaluationExpectationRequest, + dict, + ], +) +def test_create_evaluation_expectation_rest_call_success(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request_init["evaluation_expectation"] = { + "llm_criteria": {"prompt": "prompt_value"}, + "name": "name_value", + "display_name": "display_name_value", + "tags": ["tags_value1", "tags_value2"], + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "etag": "etag_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = evaluation_service.CreateEvaluationExpectationRequest.meta.fields[ + "evaluation_expectation" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "evaluation_expectation" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["evaluation_expectation"][field])): + del request_init["evaluation_expectation"][field][i][subfield] + else: + del request_init["evaluation_expectation"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation.EvaluationExpectation( + name="name_value", + display_name="display_name_value", + tags=["tags_value"], + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = evaluation.EvaluationExpectation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_evaluation_expectation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.EvaluationExpectation) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.tags == ["tags_value"] + assert response.etag == "etag_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_evaluation_expectation_rest_interceptors(null_interceptor): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EvaluationServiceRestInterceptor(), + ) + client = EvaluationServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.EvaluationServiceRestInterceptor, + "post_create_evaluation_expectation", + ) as post, mock.patch.object( + transports.EvaluationServiceRestInterceptor, + "post_create_evaluation_expectation_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "pre_create_evaluation_expectation" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = evaluation_service.CreateEvaluationExpectationRequest.pb( + evaluation_service.CreateEvaluationExpectationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = evaluation.EvaluationExpectation.to_json( + evaluation.EvaluationExpectation() + ) + req.return_value.content = return_value + + request = evaluation_service.CreateEvaluationExpectationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = evaluation.EvaluationExpectation() + post_with_metadata.return_value = evaluation.EvaluationExpectation(), metadata + + client.create_evaluation_expectation( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_evaluation_expectation_rest_bad_request( + request_type=evaluation_service.UpdateEvaluationExpectationRequest, +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "evaluation_expectation": { + "name": "projects/sample1/locations/sample2/apps/sample3/evaluationExpectations/sample4" + } + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_evaluation_expectation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.UpdateEvaluationExpectationRequest, + dict, + ], +) +def test_update_evaluation_expectation_rest_call_success(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "evaluation_expectation": { + "name": "projects/sample1/locations/sample2/apps/sample3/evaluationExpectations/sample4" + } + } + request_init["evaluation_expectation"] = { + "llm_criteria": {"prompt": "prompt_value"}, + "name": "projects/sample1/locations/sample2/apps/sample3/evaluationExpectations/sample4", + "display_name": "display_name_value", + "tags": ["tags_value1", "tags_value2"], + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "etag": "etag_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = evaluation_service.UpdateEvaluationExpectationRequest.meta.fields[ + "evaluation_expectation" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "evaluation_expectation" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["evaluation_expectation"][field])): + del request_init["evaluation_expectation"][field][i][subfield] + else: + del request_init["evaluation_expectation"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation.EvaluationExpectation( + name="name_value", + display_name="display_name_value", + tags=["tags_value"], + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = evaluation.EvaluationExpectation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_evaluation_expectation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.EvaluationExpectation) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.tags == ["tags_value"] + assert response.etag == "etag_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_evaluation_expectation_rest_interceptors(null_interceptor): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EvaluationServiceRestInterceptor(), + ) + client = EvaluationServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.EvaluationServiceRestInterceptor, + "post_update_evaluation_expectation", + ) as post, mock.patch.object( + transports.EvaluationServiceRestInterceptor, + "post_update_evaluation_expectation_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "pre_update_evaluation_expectation" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = evaluation_service.UpdateEvaluationExpectationRequest.pb( + evaluation_service.UpdateEvaluationExpectationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = evaluation.EvaluationExpectation.to_json( + evaluation.EvaluationExpectation() + ) + req.return_value.content = return_value + + request = evaluation_service.UpdateEvaluationExpectationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = evaluation.EvaluationExpectation() + post_with_metadata.return_value = evaluation.EvaluationExpectation(), metadata + + client.update_evaluation_expectation( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_evaluation_expectation_rest_bad_request( + request_type=evaluation_service.DeleteEvaluationExpectationRequest, +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/evaluationExpectations/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_evaluation_expectation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.DeleteEvaluationExpectationRequest, + dict, + ], +) +def test_delete_evaluation_expectation_rest_call_success(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/evaluationExpectations/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_evaluation_expectation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_evaluation_expectation_rest_interceptors(null_interceptor): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EvaluationServiceRestInterceptor(), + ) + client = EvaluationServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "pre_delete_evaluation_expectation" + ) as pre: + pre.assert_not_called() + pb_message = evaluation_service.DeleteEvaluationExpectationRequest.pb( + evaluation_service.DeleteEvaluationExpectationRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = evaluation_service.DeleteEvaluationExpectationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_evaluation_expectation( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_create_scheduled_evaluation_run_rest_bad_request( + request_type=evaluation_service.CreateScheduledEvaluationRunRequest, +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.create_scheduled_evaluation_run(request) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.CreateScheduledEvaluationRunRequest, + dict, + ], +) +def test_create_scheduled_evaluation_run_rest_call_success(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request_init["scheduled_evaluation_run"] = { + "name": "name_value", + "display_name": "display_name_value", + "request": { + "app": "app_value", + "evaluations": ["evaluations_value1", "evaluations_value2"], + "evaluation_dataset": "evaluation_dataset_value", + "display_name": "display_name_value", + "app_version": "app_version_value", + "config": { + "input_audio_config": { + "audio_encoding": 1, + "sample_rate_hertz": 1817, + "noise_suppression_level": "noise_suppression_level_value", + }, + "output_audio_config": {"audio_encoding": 1, "sample_rate_hertz": 1817}, + "evaluation_channel": 1, + "tool_call_behaviour": 1, + }, + "run_count": 989, + "persona_run_configs": [{"persona": "persona_value", "task_count": 1083}], + "optimization_config": { + "generate_loss_report": True, + "assistant_session": "assistant_session_value", + "report_summary": "report_summary_value", + "should_suggest_fix": True, + "status": 1, + "error_message": "error_message_value", + "loss_report": {"fields": {}}, + }, + "scheduled_evaluation_run": "scheduled_evaluation_run_value", + "golden_run_method": 1, + "generate_latency_report": True, + }, + "description": "description_value", + "scheduling_config": { + "frequency": 1, + "start_time": {"seconds": 751, "nanos": 543}, + "days_of_week": [1265, 1266], + }, + "active": True, + "last_completed_run": "last_completed_run_value", + "total_executions": 1738, + "next_scheduled_execution_time": {}, + "create_time": {}, + "created_by": "created_by_value", + "update_time": {}, + "last_updated_by": "last_updated_by_value", + "etag": "etag_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = evaluation_service.CreateScheduledEvaluationRunRequest.meta.fields[ + "scheduled_evaluation_run" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "scheduled_evaluation_run" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["scheduled_evaluation_run"][field])): + del request_init["scheduled_evaluation_run"][field][i][subfield] + else: + del request_init["scheduled_evaluation_run"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation.ScheduledEvaluationRun( + name="name_value", + display_name="display_name_value", + description="description_value", + active=True, + last_completed_run="last_completed_run_value", + total_executions=1738, + created_by="created_by_value", + last_updated_by="last_updated_by_value", + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = evaluation.ScheduledEvaluationRun.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_scheduled_evaluation_run(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.ScheduledEvaluationRun) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.active is True + assert response.last_completed_run == "last_completed_run_value" + assert response.total_executions == 1738 + assert response.created_by == "created_by_value" + assert response.last_updated_by == "last_updated_by_value" + assert response.etag == "etag_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_scheduled_evaluation_run_rest_interceptors(null_interceptor): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EvaluationServiceRestInterceptor(), + ) + client = EvaluationServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.EvaluationServiceRestInterceptor, + "post_create_scheduled_evaluation_run", + ) as post, mock.patch.object( + transports.EvaluationServiceRestInterceptor, + "post_create_scheduled_evaluation_run_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.EvaluationServiceRestInterceptor, + "pre_create_scheduled_evaluation_run", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = evaluation_service.CreateScheduledEvaluationRunRequest.pb( + evaluation_service.CreateScheduledEvaluationRunRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = evaluation.ScheduledEvaluationRun.to_json( + evaluation.ScheduledEvaluationRun() + ) + req.return_value.content = return_value + + request = evaluation_service.CreateScheduledEvaluationRunRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = evaluation.ScheduledEvaluationRun() + post_with_metadata.return_value = evaluation.ScheduledEvaluationRun(), metadata + + client.create_scheduled_evaluation_run( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_scheduled_evaluation_run_rest_bad_request( + request_type=evaluation_service.GetScheduledEvaluationRunRequest, +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/scheduledEvaluationRuns/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_scheduled_evaluation_run(request) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.GetScheduledEvaluationRunRequest, + dict, + ], +) +def test_get_scheduled_evaluation_run_rest_call_success(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/scheduledEvaluationRuns/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation.ScheduledEvaluationRun( + name="name_value", + display_name="display_name_value", + description="description_value", + active=True, + last_completed_run="last_completed_run_value", + total_executions=1738, + created_by="created_by_value", + last_updated_by="last_updated_by_value", + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = evaluation.ScheduledEvaluationRun.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get_scheduled_evaluation_run(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.ScheduledEvaluationRun) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.active is True + assert response.last_completed_run == "last_completed_run_value" + assert response.total_executions == 1738 + assert response.created_by == "created_by_value" + assert response.last_updated_by == "last_updated_by_value" + assert response.etag == "etag_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_scheduled_evaluation_run_rest_interceptors(null_interceptor): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EvaluationServiceRestInterceptor(), + ) + client = EvaluationServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "post_get_scheduled_evaluation_run" + ) as post, mock.patch.object( + transports.EvaluationServiceRestInterceptor, + "post_get_scheduled_evaluation_run_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "pre_get_scheduled_evaluation_run" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = evaluation_service.GetScheduledEvaluationRunRequest.pb( + evaluation_service.GetScheduledEvaluationRunRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = evaluation.ScheduledEvaluationRun.to_json( + evaluation.ScheduledEvaluationRun() + ) + req.return_value.content = return_value + + request = evaluation_service.GetScheduledEvaluationRunRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = evaluation.ScheduledEvaluationRun() + post_with_metadata.return_value = evaluation.ScheduledEvaluationRun(), metadata + + client.get_scheduled_evaluation_run( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_scheduled_evaluation_runs_rest_bad_request( + request_type=evaluation_service.ListScheduledEvaluationRunsRequest, +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_scheduled_evaluation_runs(request) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.ListScheduledEvaluationRunsRequest, + dict, + ], +) +def test_list_scheduled_evaluation_runs_rest_call_success(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation_service.ListScheduledEvaluationRunsResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = evaluation_service.ListScheduledEvaluationRunsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list_scheduled_evaluation_runs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScheduledEvaluationRunsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_scheduled_evaluation_runs_rest_interceptors(null_interceptor): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EvaluationServiceRestInterceptor(), + ) + client = EvaluationServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.EvaluationServiceRestInterceptor, + "post_list_scheduled_evaluation_runs", + ) as post, mock.patch.object( + transports.EvaluationServiceRestInterceptor, + "post_list_scheduled_evaluation_runs_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.EvaluationServiceRestInterceptor, + "pre_list_scheduled_evaluation_runs", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = evaluation_service.ListScheduledEvaluationRunsRequest.pb( + evaluation_service.ListScheduledEvaluationRunsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = evaluation_service.ListScheduledEvaluationRunsResponse.to_json( + evaluation_service.ListScheduledEvaluationRunsResponse() + ) + req.return_value.content = return_value + + request = evaluation_service.ListScheduledEvaluationRunsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = evaluation_service.ListScheduledEvaluationRunsResponse() + post_with_metadata.return_value = ( + evaluation_service.ListScheduledEvaluationRunsResponse(), + metadata, + ) + + client.list_scheduled_evaluation_runs( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_scheduled_evaluation_run_rest_bad_request( + request_type=evaluation_service.UpdateScheduledEvaluationRunRequest, +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "scheduled_evaluation_run": { + "name": "projects/sample1/locations/sample2/apps/sample3/scheduledEvaluationRuns/sample4" + } + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.update_scheduled_evaluation_run(request) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.UpdateScheduledEvaluationRunRequest, + dict, + ], +) +def test_update_scheduled_evaluation_run_rest_call_success(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "scheduled_evaluation_run": { + "name": "projects/sample1/locations/sample2/apps/sample3/scheduledEvaluationRuns/sample4" + } + } + request_init["scheduled_evaluation_run"] = { + "name": "projects/sample1/locations/sample2/apps/sample3/scheduledEvaluationRuns/sample4", + "display_name": "display_name_value", + "request": { + "app": "app_value", + "evaluations": ["evaluations_value1", "evaluations_value2"], + "evaluation_dataset": "evaluation_dataset_value", + "display_name": "display_name_value", + "app_version": "app_version_value", + "config": { + "input_audio_config": { + "audio_encoding": 1, + "sample_rate_hertz": 1817, + "noise_suppression_level": "noise_suppression_level_value", + }, + "output_audio_config": {"audio_encoding": 1, "sample_rate_hertz": 1817}, + "evaluation_channel": 1, + "tool_call_behaviour": 1, + }, + "run_count": 989, + "persona_run_configs": [{"persona": "persona_value", "task_count": 1083}], + "optimization_config": { + "generate_loss_report": True, + "assistant_session": "assistant_session_value", + "report_summary": "report_summary_value", + "should_suggest_fix": True, + "status": 1, + "error_message": "error_message_value", + "loss_report": {"fields": {}}, + }, + "scheduled_evaluation_run": "scheduled_evaluation_run_value", + "golden_run_method": 1, + "generate_latency_report": True, + }, + "description": "description_value", + "scheduling_config": { + "frequency": 1, + "start_time": {"seconds": 751, "nanos": 543}, + "days_of_week": [1265, 1266], + }, + "active": True, + "last_completed_run": "last_completed_run_value", + "total_executions": 1738, + "next_scheduled_execution_time": {}, + "create_time": {}, + "created_by": "created_by_value", + "update_time": {}, + "last_updated_by": "last_updated_by_value", + "etag": "etag_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = evaluation_service.UpdateScheduledEvaluationRunRequest.meta.fields[ + "scheduled_evaluation_run" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "scheduled_evaluation_run" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["scheduled_evaluation_run"][field])): + del request_init["scheduled_evaluation_run"][field][i][subfield] + else: + del request_init["scheduled_evaluation_run"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation.ScheduledEvaluationRun( + name="name_value", + display_name="display_name_value", + description="description_value", + active=True, + last_completed_run="last_completed_run_value", + total_executions=1738, + created_by="created_by_value", + last_updated_by="last_updated_by_value", + etag="etag_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = evaluation.ScheduledEvaluationRun.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_scheduled_evaluation_run(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.ScheduledEvaluationRun) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.active is True + assert response.last_completed_run == "last_completed_run_value" + assert response.total_executions == 1738 + assert response.created_by == "created_by_value" + assert response.last_updated_by == "last_updated_by_value" + assert response.etag == "etag_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_scheduled_evaluation_run_rest_interceptors(null_interceptor): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EvaluationServiceRestInterceptor(), + ) + client = EvaluationServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.EvaluationServiceRestInterceptor, + "post_update_scheduled_evaluation_run", + ) as post, mock.patch.object( + transports.EvaluationServiceRestInterceptor, + "post_update_scheduled_evaluation_run_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.EvaluationServiceRestInterceptor, + "pre_update_scheduled_evaluation_run", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = evaluation_service.UpdateScheduledEvaluationRunRequest.pb( + evaluation_service.UpdateScheduledEvaluationRunRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = evaluation.ScheduledEvaluationRun.to_json( + evaluation.ScheduledEvaluationRun() + ) + req.return_value.content = return_value + + request = evaluation_service.UpdateScheduledEvaluationRunRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = evaluation.ScheduledEvaluationRun() + post_with_metadata.return_value = evaluation.ScheduledEvaluationRun(), metadata + + client.update_scheduled_evaluation_run( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_scheduled_evaluation_run_rest_bad_request( + request_type=evaluation_service.DeleteScheduledEvaluationRunRequest, +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/scheduledEvaluationRuns/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_scheduled_evaluation_run(request) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.DeleteScheduledEvaluationRunRequest, + dict, + ], +) +def test_delete_scheduled_evaluation_run_rest_call_success(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/scheduledEvaluationRuns/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "" + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_scheduled_evaluation_run(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_scheduled_evaluation_run_rest_interceptors(null_interceptor): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EvaluationServiceRestInterceptor(), + ) + client = EvaluationServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.EvaluationServiceRestInterceptor, + "pre_delete_scheduled_evaluation_run", + ) as pre: + pre.assert_not_called() + pb_message = evaluation_service.DeleteScheduledEvaluationRunRequest.pb( + evaluation_service.DeleteScheduledEvaluationRunRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + request = evaluation_service.DeleteScheduledEvaluationRunRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_scheduled_evaluation_run( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_test_persona_voice_rest_bad_request( + request_type=evaluation_service.TestPersonaVoiceRequest, +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"app": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.test_persona_voice(request) + + +@pytest.mark.parametrize( + "request_type", + [ + evaluation_service.TestPersonaVoiceRequest, + dict, + ], +) +def test_test_persona_voice_rest_call_success(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"app": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = evaluation_service.TestPersonaVoiceResponse( + audio=b"audio_blob", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = evaluation_service.TestPersonaVoiceResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.test_persona_voice(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation_service.TestPersonaVoiceResponse) + assert response.audio == b"audio_blob" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_test_persona_voice_rest_interceptors(null_interceptor): + transport = transports.EvaluationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.EvaluationServiceRestInterceptor(), + ) + client = EvaluationServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "post_test_persona_voice" + ) as post, mock.patch.object( + transports.EvaluationServiceRestInterceptor, + "post_test_persona_voice_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.EvaluationServiceRestInterceptor, "pre_test_persona_voice" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = evaluation_service.TestPersonaVoiceRequest.pb( + evaluation_service.TestPersonaVoiceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = evaluation_service.TestPersonaVoiceResponse.to_json( + evaluation_service.TestPersonaVoiceResponse() + ) + req.return_value.content = return_value + + request = evaluation_service.TestPersonaVoiceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = evaluation_service.TestPersonaVoiceResponse() + post_with_metadata.return_value = ( + evaluation_service.TestPersonaVoiceResponse(), + metadata, + ) + + client.test_persona_voice( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_location(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.GetLocationRequest, + dict, + ], +) +def test_get_location_rest(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_list_locations_rest_bad_request( + request_type=locations_pb2.ListLocationsRequest, +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"name": "projects/sample1"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_locations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.ListLocationsRequest, + dict, + ], +) +def test_list_locations_rest(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_cancel_operation_rest_bad_request( + request_type=operations_pb2.CancelOperationRequest, +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_rest_bad_request( + request_type=operations_pb2.DeleteOperationRequest, +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_run_evaluation_empty_call_rest(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.run_evaluation), "__call__") as call: + client.run_evaluation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation.RunEvaluationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_upload_evaluation_audio_empty_call_rest(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.upload_evaluation_audio), "__call__" + ) as call: + client.upload_evaluation_audio(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.UploadEvaluationAudioRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_evaluation_empty_call_rest(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation), "__call__" + ) as call: + client.create_evaluation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.CreateEvaluationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_generate_evaluation_empty_call_rest(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_evaluation), "__call__" + ) as call: + client.generate_evaluation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.GenerateEvaluationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_evaluations_empty_call_rest(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_evaluations), "__call__" + ) as call: + client.import_evaluations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.ImportEvaluationsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_evaluation_dataset_empty_call_rest(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation_dataset), "__call__" + ) as call: + client.create_evaluation_dataset(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.CreateEvaluationDatasetRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_evaluation_empty_call_rest(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_evaluation), "__call__" + ) as call: + client.update_evaluation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.UpdateEvaluationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_evaluation_dataset_empty_call_rest(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_evaluation_dataset), "__call__" + ) as call: + client.update_evaluation_dataset(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.UpdateEvaluationDatasetRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_evaluation_empty_call_rest(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation), "__call__" + ) as call: + client.delete_evaluation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.DeleteEvaluationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_evaluation_result_empty_call_rest(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_result), "__call__" + ) as call: + client.delete_evaluation_result(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.DeleteEvaluationResultRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_evaluation_dataset_empty_call_rest(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_dataset), "__call__" + ) as call: + client.delete_evaluation_dataset(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.DeleteEvaluationDatasetRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_evaluation_run_empty_call_rest(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_run), "__call__" + ) as call: + client.delete_evaluation_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.DeleteEvaluationRunRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_evaluation_empty_call_rest(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_evaluation), "__call__") as call: + client.get_evaluation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.GetEvaluationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_evaluation_result_empty_call_rest(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_evaluation_result), "__call__" + ) as call: + client.get_evaluation_result(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.GetEvaluationResultRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_evaluation_dataset_empty_call_rest(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_evaluation_dataset), "__call__" + ) as call: + client.get_evaluation_dataset(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.GetEvaluationDatasetRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_evaluation_run_empty_call_rest(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_evaluation_run), "__call__" + ) as call: + client.get_evaluation_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.GetEvaluationRunRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_evaluations_empty_call_rest(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_evaluations), "__call__") as call: + client.list_evaluations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.ListEvaluationsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_evaluation_results_empty_call_rest(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_results), "__call__" + ) as call: + client.list_evaluation_results(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.ListEvaluationResultsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_evaluation_datasets_empty_call_rest(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_datasets), "__call__" + ) as call: + client.list_evaluation_datasets(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.ListEvaluationDatasetsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_evaluation_runs_empty_call_rest(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_runs), "__call__" + ) as call: + client.list_evaluation_runs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.ListEvaluationRunsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_evaluation_expectations_empty_call_rest(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluation_expectations), "__call__" + ) as call: + client.list_evaluation_expectations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.ListEvaluationExpectationsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_evaluation_expectation_empty_call_rest(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_evaluation_expectation), "__call__" + ) as call: + client.get_evaluation_expectation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.GetEvaluationExpectationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_evaluation_expectation_empty_call_rest(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_evaluation_expectation), "__call__" + ) as call: + client.create_evaluation_expectation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.CreateEvaluationExpectationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_evaluation_expectation_empty_call_rest(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_evaluation_expectation), "__call__" + ) as call: + client.update_evaluation_expectation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.UpdateEvaluationExpectationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_evaluation_expectation_empty_call_rest(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_evaluation_expectation), "__call__" + ) as call: + client.delete_evaluation_expectation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.DeleteEvaluationExpectationRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_scheduled_evaluation_run_empty_call_rest(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_scheduled_evaluation_run), "__call__" + ) as call: + client.create_scheduled_evaluation_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.CreateScheduledEvaluationRunRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_scheduled_evaluation_run_empty_call_rest(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_scheduled_evaluation_run), "__call__" + ) as call: + client.get_scheduled_evaluation_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.GetScheduledEvaluationRunRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_scheduled_evaluation_runs_empty_call_rest(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_scheduled_evaluation_runs), "__call__" + ) as call: + client.list_scheduled_evaluation_runs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.ListScheduledEvaluationRunsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_scheduled_evaluation_run_empty_call_rest(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_scheduled_evaluation_run), "__call__" + ) as call: + client.update_scheduled_evaluation_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.UpdateScheduledEvaluationRunRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_delete_scheduled_evaluation_run_empty_call_rest(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_scheduled_evaluation_run), "__call__" + ) as call: + client.delete_scheduled_evaluation_run(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.DeleteScheduledEvaluationRunRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_test_persona_voice_empty_call_rest(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.test_persona_voice), "__call__" + ) as call: + client.test_persona_voice(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = evaluation_service.TestPersonaVoiceRequest() + + assert args[0] == request_msg + + +def test_evaluation_service_rest_lro_client(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.EvaluationServiceGrpcTransport, + ) + + +def test_evaluation_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.EvaluationServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_evaluation_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.ces_v1beta.services.evaluation_service.transports.EvaluationServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.EvaluationServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "run_evaluation", + "upload_evaluation_audio", + "create_evaluation", + "generate_evaluation", + "import_evaluations", + "create_evaluation_dataset", + "update_evaluation", + "update_evaluation_dataset", + "delete_evaluation", + "delete_evaluation_result", + "delete_evaluation_dataset", + "delete_evaluation_run", + "get_evaluation", + "get_evaluation_result", + "get_evaluation_dataset", + "get_evaluation_run", + "list_evaluations", + "list_evaluation_results", + "list_evaluation_datasets", + "list_evaluation_runs", + "list_evaluation_expectations", + "get_evaluation_expectation", + "create_evaluation_expectation", + "update_evaluation_expectation", + "delete_evaluation_expectation", + "create_scheduled_evaluation_run", + "get_scheduled_evaluation_run", + "list_scheduled_evaluation_runs", + "update_scheduled_evaluation_run", + "delete_scheduled_evaluation_run", + "test_persona_voice", + "get_location", + "list_locations", + "get_operation", + "cancel_operation", + "delete_operation", + "list_operations", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_evaluation_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.ces_v1beta.services.evaluation_service.transports.EvaluationServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EvaluationServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/ces", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +def test_evaluation_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.ces_v1beta.services.evaluation_service.transports.EvaluationServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EvaluationServiceTransport() + adc.assert_called_once() + + +def test_evaluation_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + EvaluationServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/ces", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.EvaluationServiceGrpcTransport, + transports.EvaluationServiceGrpcAsyncIOTransport, + ], +) +def test_evaluation_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/ces", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.EvaluationServiceGrpcTransport, + transports.EvaluationServiceGrpcAsyncIOTransport, + transports.EvaluationServiceRestTransport, + ], +) +def test_evaluation_service_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EvaluationServiceGrpcTransport, grpc_helpers), + (transports.EvaluationServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_evaluation_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "ces.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/ces", + "https://www.googleapis.com/auth/cloud-platform", + ), + scopes=["1", "2"], + default_host="ces.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.EvaluationServiceGrpcTransport, + transports.EvaluationServiceGrpcAsyncIOTransport, + ], +) +def test_evaluation_service_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_evaluation_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.EvaluationServiceRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_evaluation_service_host_no_port(transport_name): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint="ces.googleapis.com"), + transport=transport_name, + ) + assert client.transport._host == ( + "ces.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://ces.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_evaluation_service_host_with_port(transport_name): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="ces.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "ces.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://ces.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_evaluation_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = EvaluationServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = EvaluationServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.run_evaluation._session + session2 = client2.transport.run_evaluation._session + assert session1 != session2 + session1 = client1.transport.upload_evaluation_audio._session + session2 = client2.transport.upload_evaluation_audio._session + assert session1 != session2 + session1 = client1.transport.create_evaluation._session + session2 = client2.transport.create_evaluation._session + assert session1 != session2 + session1 = client1.transport.generate_evaluation._session + session2 = client2.transport.generate_evaluation._session + assert session1 != session2 + session1 = client1.transport.import_evaluations._session + session2 = client2.transport.import_evaluations._session + assert session1 != session2 + session1 = client1.transport.create_evaluation_dataset._session + session2 = client2.transport.create_evaluation_dataset._session + assert session1 != session2 + session1 = client1.transport.update_evaluation._session + session2 = client2.transport.update_evaluation._session + assert session1 != session2 + session1 = client1.transport.update_evaluation_dataset._session + session2 = client2.transport.update_evaluation_dataset._session + assert session1 != session2 + session1 = client1.transport.delete_evaluation._session + session2 = client2.transport.delete_evaluation._session + assert session1 != session2 + session1 = client1.transport.delete_evaluation_result._session + session2 = client2.transport.delete_evaluation_result._session + assert session1 != session2 + session1 = client1.transport.delete_evaluation_dataset._session + session2 = client2.transport.delete_evaluation_dataset._session + assert session1 != session2 + session1 = client1.transport.delete_evaluation_run._session + session2 = client2.transport.delete_evaluation_run._session + assert session1 != session2 + session1 = client1.transport.get_evaluation._session + session2 = client2.transport.get_evaluation._session + assert session1 != session2 + session1 = client1.transport.get_evaluation_result._session + session2 = client2.transport.get_evaluation_result._session + assert session1 != session2 + session1 = client1.transport.get_evaluation_dataset._session + session2 = client2.transport.get_evaluation_dataset._session + assert session1 != session2 + session1 = client1.transport.get_evaluation_run._session + session2 = client2.transport.get_evaluation_run._session + assert session1 != session2 + session1 = client1.transport.list_evaluations._session + session2 = client2.transport.list_evaluations._session + assert session1 != session2 + session1 = client1.transport.list_evaluation_results._session + session2 = client2.transport.list_evaluation_results._session + assert session1 != session2 + session1 = client1.transport.list_evaluation_datasets._session + session2 = client2.transport.list_evaluation_datasets._session + assert session1 != session2 + session1 = client1.transport.list_evaluation_runs._session + session2 = client2.transport.list_evaluation_runs._session + assert session1 != session2 + session1 = client1.transport.list_evaluation_expectations._session + session2 = client2.transport.list_evaluation_expectations._session + assert session1 != session2 + session1 = client1.transport.get_evaluation_expectation._session + session2 = client2.transport.get_evaluation_expectation._session + assert session1 != session2 + session1 = client1.transport.create_evaluation_expectation._session + session2 = client2.transport.create_evaluation_expectation._session + assert session1 != session2 + session1 = client1.transport.update_evaluation_expectation._session + session2 = client2.transport.update_evaluation_expectation._session + assert session1 != session2 + session1 = client1.transport.delete_evaluation_expectation._session + session2 = client2.transport.delete_evaluation_expectation._session + assert session1 != session2 + session1 = client1.transport.create_scheduled_evaluation_run._session + session2 = client2.transport.create_scheduled_evaluation_run._session + assert session1 != session2 + session1 = client1.transport.get_scheduled_evaluation_run._session + session2 = client2.transport.get_scheduled_evaluation_run._session + assert session1 != session2 + session1 = client1.transport.list_scheduled_evaluation_runs._session + session2 = client2.transport.list_scheduled_evaluation_runs._session + assert session1 != session2 + session1 = client1.transport.update_scheduled_evaluation_run._session + session2 = client2.transport.update_scheduled_evaluation_run._session + assert session1 != session2 + session1 = client1.transport.delete_scheduled_evaluation_run._session + session2 = client2.transport.delete_scheduled_evaluation_run._session + assert session1 != session2 + session1 = client1.transport.test_persona_voice._session + session2 = client2.transport.test_persona_voice._session + assert session1 != session2 + + +def test_evaluation_service_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.EvaluationServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_evaluation_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.EvaluationServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.filterwarnings("ignore::FutureWarning") +@pytest.mark.parametrize( + "transport_class", + [ + transports.EvaluationServiceGrpcTransport, + transports.EvaluationServiceGrpcAsyncIOTransport, + ], +) +def test_evaluation_service_transport_channel_mtls_with_client_cert_source( + transport_class, +): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.EvaluationServiceGrpcTransport, + transports.EvaluationServiceGrpcAsyncIOTransport, + ], +) +def test_evaluation_service_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_evaluation_service_grpc_lro_client(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_evaluation_service_grpc_lro_async_client(): + client = EvaluationServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_agent_path(): + project = "squid" + location = "clam" + app = "whelk" + agent = "octopus" + expected = ( + "projects/{project}/locations/{location}/apps/{app}/agents/{agent}".format( + project=project, + location=location, + app=app, + agent=agent, + ) + ) + actual = EvaluationServiceClient.agent_path(project, location, app, agent) + assert expected == actual + + +def test_parse_agent_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "app": "cuttlefish", + "agent": "mussel", + } + path = EvaluationServiceClient.agent_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_agent_path(path) + assert expected == actual + + +def test_app_path(): + project = "winkle" + location = "nautilus" + app = "scallop" + expected = "projects/{project}/locations/{location}/apps/{app}".format( + project=project, + location=location, + app=app, + ) + actual = EvaluationServiceClient.app_path(project, location, app) + assert expected == actual + + +def test_parse_app_path(): + expected = { + "project": "abalone", + "location": "squid", + "app": "clam", + } + path = EvaluationServiceClient.app_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_app_path(path) + assert expected == actual + + +def test_app_version_path(): + project = "whelk" + location = "octopus" + app = "oyster" + version = "nudibranch" + expected = ( + "projects/{project}/locations/{location}/apps/{app}/versions/{version}".format( + project=project, + location=location, + app=app, + version=version, + ) + ) + actual = EvaluationServiceClient.app_version_path(project, location, app, version) + assert expected == actual + + +def test_parse_app_version_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "app": "winkle", + "version": "nautilus", + } + path = EvaluationServiceClient.app_version_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_app_version_path(path) + assert expected == actual + + +def test_changelog_path(): + project = "scallop" + location = "abalone" + app = "squid" + changelog = "clam" + expected = "projects/{project}/locations/{location}/apps/{app}/changelogs/{changelog}".format( + project=project, + location=location, + app=app, + changelog=changelog, + ) + actual = EvaluationServiceClient.changelog_path(project, location, app, changelog) + assert expected == actual + + +def test_parse_changelog_path(): + expected = { + "project": "whelk", + "location": "octopus", + "app": "oyster", + "changelog": "nudibranch", + } + path = EvaluationServiceClient.changelog_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_changelog_path(path) + assert expected == actual + + +def test_conversation_path(): + project = "cuttlefish" + location = "mussel" + app = "winkle" + conversation = "nautilus" + expected = "projects/{project}/locations/{location}/apps/{app}/conversations/{conversation}".format( + project=project, + location=location, + app=app, + conversation=conversation, + ) + actual = EvaluationServiceClient.conversation_path( + project, location, app, conversation + ) + assert expected == actual + + +def test_parse_conversation_path(): + expected = { + "project": "scallop", + "location": "abalone", + "app": "squid", + "conversation": "clam", + } + path = EvaluationServiceClient.conversation_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_conversation_path(path) + assert expected == actual + + +def test_evaluation_path(): + project = "whelk" + location = "octopus" + app = "oyster" + evaluation = "nudibranch" + expected = "projects/{project}/locations/{location}/apps/{app}/evaluations/{evaluation}".format( + project=project, + location=location, + app=app, + evaluation=evaluation, + ) + actual = EvaluationServiceClient.evaluation_path(project, location, app, evaluation) + assert expected == actual + + +def test_parse_evaluation_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "app": "winkle", + "evaluation": "nautilus", + } + path = EvaluationServiceClient.evaluation_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_evaluation_path(path) + assert expected == actual + + +def test_evaluation_dataset_path(): + project = "scallop" + location = "abalone" + app = "squid" + evaluation_dataset = "clam" + expected = "projects/{project}/locations/{location}/apps/{app}/evaluationDatasets/{evaluation_dataset}".format( + project=project, + location=location, + app=app, + evaluation_dataset=evaluation_dataset, + ) + actual = EvaluationServiceClient.evaluation_dataset_path( + project, location, app, evaluation_dataset + ) + assert expected == actual + + +def test_parse_evaluation_dataset_path(): + expected = { + "project": "whelk", + "location": "octopus", + "app": "oyster", + "evaluation_dataset": "nudibranch", + } + path = EvaluationServiceClient.evaluation_dataset_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_evaluation_dataset_path(path) + assert expected == actual + + +def test_evaluation_expectation_path(): + project = "cuttlefish" + location = "mussel" + app = "winkle" + evaluation_expectation = "nautilus" + expected = "projects/{project}/locations/{location}/apps/{app}/evaluationExpectations/{evaluation_expectation}".format( + project=project, + location=location, + app=app, + evaluation_expectation=evaluation_expectation, + ) + actual = EvaluationServiceClient.evaluation_expectation_path( + project, location, app, evaluation_expectation + ) + assert expected == actual + + +def test_parse_evaluation_expectation_path(): + expected = { + "project": "scallop", + "location": "abalone", + "app": "squid", + "evaluation_expectation": "clam", + } + path = EvaluationServiceClient.evaluation_expectation_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_evaluation_expectation_path(path) + assert expected == actual + + +def test_evaluation_result_path(): + project = "whelk" + location = "octopus" + app = "oyster" + evaluation = "nudibranch" + evaluation_result = "cuttlefish" + expected = "projects/{project}/locations/{location}/apps/{app}/evaluations/{evaluation}/results/{evaluation_result}".format( + project=project, + location=location, + app=app, + evaluation=evaluation, + evaluation_result=evaluation_result, + ) + actual = EvaluationServiceClient.evaluation_result_path( + project, location, app, evaluation, evaluation_result + ) + assert expected == actual + + +def test_parse_evaluation_result_path(): + expected = { + "project": "mussel", + "location": "winkle", + "app": "nautilus", + "evaluation": "scallop", + "evaluation_result": "abalone", + } + path = EvaluationServiceClient.evaluation_result_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_evaluation_result_path(path) + assert expected == actual + + +def test_evaluation_run_path(): + project = "squid" + location = "clam" + app = "whelk" + evaluation_run = "octopus" + expected = "projects/{project}/locations/{location}/apps/{app}/evaluationRuns/{evaluation_run}".format( + project=project, + location=location, + app=app, + evaluation_run=evaluation_run, + ) + actual = EvaluationServiceClient.evaluation_run_path( + project, location, app, evaluation_run + ) + assert expected == actual + + +def test_parse_evaluation_run_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "app": "cuttlefish", + "evaluation_run": "mussel", + } + path = EvaluationServiceClient.evaluation_run_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_evaluation_run_path(path) + assert expected == actual + + +def test_guardrail_path(): + project = "winkle" + location = "nautilus" + app = "scallop" + guardrail = "abalone" + expected = "projects/{project}/locations/{location}/apps/{app}/guardrails/{guardrail}".format( + project=project, + location=location, + app=app, + guardrail=guardrail, + ) + actual = EvaluationServiceClient.guardrail_path(project, location, app, guardrail) + assert expected == actual + + +def test_parse_guardrail_path(): + expected = { + "project": "squid", + "location": "clam", + "app": "whelk", + "guardrail": "octopus", + } + path = EvaluationServiceClient.guardrail_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_guardrail_path(path) + assert expected == actual + + +def test_scheduled_evaluation_run_path(): + project = "oyster" + location = "nudibranch" + app = "cuttlefish" + scheduled_evaluation_run = "mussel" + expected = "projects/{project}/locations/{location}/apps/{app}/scheduledEvaluationRuns/{scheduled_evaluation_run}".format( + project=project, + location=location, + app=app, + scheduled_evaluation_run=scheduled_evaluation_run, + ) + actual = EvaluationServiceClient.scheduled_evaluation_run_path( + project, location, app, scheduled_evaluation_run + ) + assert expected == actual + + +def test_parse_scheduled_evaluation_run_path(): + expected = { + "project": "winkle", + "location": "nautilus", + "app": "scallop", + "scheduled_evaluation_run": "abalone", + } + path = EvaluationServiceClient.scheduled_evaluation_run_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_scheduled_evaluation_run_path(path) + assert expected == actual + + +def test_tool_path(): + project = "squid" + location = "clam" + app = "whelk" + tool = "octopus" + expected = "projects/{project}/locations/{location}/apps/{app}/tools/{tool}".format( + project=project, + location=location, + app=app, + tool=tool, + ) + actual = EvaluationServiceClient.tool_path(project, location, app, tool) + assert expected == actual + + +def test_parse_tool_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "app": "cuttlefish", + "tool": "mussel", + } + path = EvaluationServiceClient.tool_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_tool_path(path) + assert expected == actual + + +def test_toolset_path(): + project = "winkle" + location = "nautilus" + app = "scallop" + toolset = "abalone" + expected = ( + "projects/{project}/locations/{location}/apps/{app}/toolsets/{toolset}".format( + project=project, + location=location, + app=app, + toolset=toolset, + ) + ) + actual = EvaluationServiceClient.toolset_path(project, location, app, toolset) + assert expected == actual + + +def test_parse_toolset_path(): + expected = { + "project": "squid", + "location": "clam", + "app": "whelk", + "toolset": "octopus", + } + path = EvaluationServiceClient.toolset_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_toolset_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = EvaluationServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = EvaluationServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = EvaluationServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = EvaluationServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = EvaluationServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = EvaluationServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format( + project=project, + ) + actual = EvaluationServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = EvaluationServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = EvaluationServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = EvaluationServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = EvaluationServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.EvaluationServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.EvaluationServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = EvaluationServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_delete_operation(transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc_asyncio"): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_operation_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_delete_operation_from_dict(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc_asyncio"): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_cancel_operation_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_cancel_operation_from_dict(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_get_operation_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_get_operation_from_dict(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_list_operations_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_list_operations_from_dict(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_locations(transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc_asyncio"): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_list_locations_field_headers(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_locations_field_headers_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_list_locations_from_dict(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_location(transport: str = "grpc"): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + response = client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_get_location_field_headers(): + client = EvaluationServiceClient(credentials=ga_credentials.AnonymousCredentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() + + client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations/abc", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_location_field_headers_async(): + client = EvaluationServiceAsyncClient(credentials=async_anonymous_credentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations/abc", + ) in kw["metadata"] + + +def test_get_location_from_dict(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + response = client.get_location( + request={ + "name": "locations/abc", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_location_from_dict_async(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close_grpc(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = EvaluationServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "rest", + "grpc", + ] + for transport in transports: + client = EvaluationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (EvaluationServiceClient, transports.EvaluationServiceGrpcTransport), + ( + EvaluationServiceAsyncClient, + transports.EvaluationServiceGrpcAsyncIOTransport, + ), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/packages/google-cloud-ces/tests/unit/gapic/ces_v1beta/test_session_service.py b/packages/google-cloud-ces/tests/unit/gapic/ces_v1beta/test_session_service.py new file mode 100644 index 000000000000..ccf11e6ffc6b --- /dev/null +++ b/packages/google-cloud-ces/tests/unit/gapic/ces_v1beta/test_session_service.py @@ -0,0 +1,4188 @@ +# -*- coding: utf-8 -*- +# 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. +# +import os + +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import json +import math +from collections.abc import AsyncIterable, Iterable, Mapping, Sequence + +import grpc +import pytest +from google.api_core import api_core_version +from google.protobuf import json_format +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +import google.auth +import google.protobuf.struct_pb2 as struct_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.api_core import ( + client_options, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + path_template, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account + +from google.cloud.ces_v1beta.services.session_service import ( + SessionServiceAsyncClient, + SessionServiceClient, + transports, +) +from google.cloud.ces_v1beta.types import example, session_service, toolset_tool + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert SessionServiceClient._get_default_mtls_endpoint(None) is None + assert ( + SessionServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + SessionServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + SessionServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + SessionServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + SessionServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + ) + + +def test__read_environment_variables(): + assert SessionServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert SessionServiceClient._read_environment_variables() == ( + True, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert SessionServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with pytest.raises(ValueError) as excinfo: + SessionServiceClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + else: + assert SessionServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert SessionServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert SessionServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert SessionServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + SessionServiceClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert SessionServiceClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + + +def test_use_client_cert_effective(): + # Test case 1: Test when `should_use_client_cert` returns True. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch( + "google.auth.transport.mtls.should_use_client_cert", return_value=True + ): + assert SessionServiceClient._use_client_cert_effective() is True + + # Test case 2: Test when `should_use_client_cert` returns False. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should NOT be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch( + "google.auth.transport.mtls.should_use_client_cert", return_value=False + ): + assert SessionServiceClient._use_client_cert_effective() is False + + # Test case 3: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "true". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert SessionServiceClient._use_client_cert_effective() is True + + # Test case 4: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"} + ): + assert SessionServiceClient._use_client_cert_effective() is False + + # Test case 5: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "True". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "True"}): + assert SessionServiceClient._use_client_cert_effective() is True + + # Test case 6: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "False". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"} + ): + assert SessionServiceClient._use_client_cert_effective() is False + + # Test case 7: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "TRUE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "TRUE"}): + assert SessionServiceClient._use_client_cert_effective() is True + + # Test case 8: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "FALSE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"} + ): + assert SessionServiceClient._use_client_cert_effective() is False + + # Test case 9: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not set. + # In this case, the method should return False, which is the default value. + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, clear=True): + assert SessionServiceClient._use_client_cert_effective() is False + + # Test case 10: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should raise a ValueError as the environment variable must be either + # "true" or "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} + ): + with pytest.raises(ValueError): + SessionServiceClient._use_client_cert_effective() + + # Test case 11: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should return False as the environment variable is set to an invalid value. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} + ): + assert SessionServiceClient._use_client_cert_effective() is False + + # Test case 12: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is unset. Also, + # the GOOGLE_API_CONFIG environment variable is unset. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": ""}): + with mock.patch.dict(os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": ""}): + assert SessionServiceClient._use_client_cert_effective() is False + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert SessionServiceClient._get_client_cert_source(None, False) is None + assert ( + SessionServiceClient._get_client_cert_source(mock_provided_cert_source, False) + is None + ) + assert ( + SessionServiceClient._get_client_cert_source(mock_provided_cert_source, True) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + SessionServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + SessionServiceClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + SessionServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SessionServiceClient), +) +@mock.patch.object( + SessionServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SessionServiceAsyncClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = SessionServiceClient._DEFAULT_UNIVERSE + default_endpoint = SessionServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = SessionServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + SessionServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + SessionServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == SessionServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + SessionServiceClient._get_api_endpoint(None, None, default_universe, "auto") + == default_endpoint + ) + assert ( + SessionServiceClient._get_api_endpoint(None, None, default_universe, "always") + == SessionServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + SessionServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == SessionServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + SessionServiceClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + SessionServiceClient._get_api_endpoint(None, None, default_universe, "never") + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + SessionServiceClient._get_api_endpoint( + None, mock_client_cert_source, mock_universe, "auto" + ) + assert ( + str(excinfo.value) + == "mTLS is not supported in any universe other than googleapis.com." + ) + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert ( + SessionServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + SessionServiceClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + SessionServiceClient._get_universe_domain(None, None) + == SessionServiceClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + SessionServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize( + "error_code,cred_info_json,show_cred_info", + [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False), + ], +) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = SessionServiceClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + + +@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = SessionServiceClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (SessionServiceClient, "grpc"), + (SessionServiceAsyncClient, "grpc_asyncio"), + (SessionServiceClient, "rest"), + ], +) +def test_session_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "ces.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://ces.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.SessionServiceGrpcTransport, "grpc"), + (transports.SessionServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.SessionServiceRestTransport, "rest"), + ], +) +def test_session_service_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (SessionServiceClient, "grpc"), + (SessionServiceAsyncClient, "grpc_asyncio"), + (SessionServiceClient, "rest"), + ], +) +def test_session_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "ces.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://ces.googleapis.com" + ) + + +def test_session_service_client_get_transport_class(): + transport = SessionServiceClient.get_transport_class() + available_transports = [ + transports.SessionServiceGrpcTransport, + transports.SessionServiceRestTransport, + ] + assert transport in available_transports + + transport = SessionServiceClient.get_transport_class("grpc") + assert transport == transports.SessionServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (SessionServiceClient, transports.SessionServiceGrpcTransport, "grpc"), + ( + SessionServiceAsyncClient, + transports.SessionServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (SessionServiceClient, transports.SessionServiceRestTransport, "rest"), + ], +) +@mock.patch.object( + SessionServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SessionServiceClient), +) +@mock.patch.object( + SessionServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SessionServiceAsyncClient), +) +def test_session_service_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(SessionServiceClient, "get_transport_class") as gtc: + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(SessionServiceClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (SessionServiceClient, transports.SessionServiceGrpcTransport, "grpc", "true"), + ( + SessionServiceAsyncClient, + transports.SessionServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (SessionServiceClient, transports.SessionServiceGrpcTransport, "grpc", "false"), + ( + SessionServiceAsyncClient, + transports.SessionServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + (SessionServiceClient, transports.SessionServiceRestTransport, "rest", "true"), + (SessionServiceClient, transports.SessionServiceRestTransport, "rest", "false"), + ], +) +@mock.patch.object( + SessionServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SessionServiceClient), +) +@mock.patch.object( + SessionServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SessionServiceAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_session_service_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class", [SessionServiceClient, SessionServiceAsyncClient] +) +@mock.patch.object( + SessionServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(SessionServiceClient), +) +@mock.patch.object( + SessionServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(SessionServiceAsyncClient), +) +def test_session_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset. + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source() + ) + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + +@pytest.mark.parametrize( + "client_class", [SessionServiceClient, SessionServiceAsyncClient] +) +@mock.patch.object( + SessionServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SessionServiceClient), +) +@mock.patch.object( + SessionServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SessionServiceAsyncClient), +) +def test_session_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = SessionServiceClient._DEFAULT_UNIVERSE + default_endpoint = SessionServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = SessionServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (SessionServiceClient, transports.SessionServiceGrpcTransport, "grpc"), + ( + SessionServiceAsyncClient, + transports.SessionServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (SessionServiceClient, transports.SessionServiceRestTransport, "rest"), + ], +) +def test_session_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + SessionServiceClient, + transports.SessionServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + SessionServiceAsyncClient, + transports.SessionServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + (SessionServiceClient, transports.SessionServiceRestTransport, "rest", None), + ], +) +def test_session_service_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_session_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.ces_v1beta.services.session_service.transports.SessionServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = SessionServiceClient( + client_options={"api_endpoint": "squid.clam.whelk"} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + SessionServiceClient, + transports.SessionServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + SessionServiceAsyncClient, + transports.SessionServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_session_service_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object(grpc_helpers, "create_channel") as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "ces.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + "https://www.googleapis.com/auth/ces", + "https://www.googleapis.com/auth/cloud-platform", + ), + scopes=None, + default_host="ces.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + session_service.RunSessionRequest, + dict, + ], +) +def test_run_session(request_type, transport: str = "grpc"): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.run_session), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = session_service.RunSessionResponse() + response = client.run_session(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = session_service.RunSessionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, session_service.RunSessionResponse) + + +def test_run_session_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = session_service.RunSessionRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.run_session), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.run_session(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == session_service.RunSessionRequest() + + +def test_run_session_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.run_session in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.run_session] = mock_rpc + request = {} + client.run_session(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.run_session(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_run_session_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SessionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.run_session + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.run_session + ] = mock_rpc + + request = {} + await client.run_session(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.run_session(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_run_session_async( + transport: str = "grpc_asyncio", request_type=session_service.RunSessionRequest +): + client = SessionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.run_session), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + session_service.RunSessionResponse() + ) + response = await client.run_session(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = session_service.RunSessionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, session_service.RunSessionResponse) + + +@pytest.mark.asyncio +async def test_run_session_async_from_dict(): + await test_run_session_async(request_type=dict) + + +def test_run_session_field_headers(): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = session_service.RunSessionRequest() + + request.config.session = "session_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.run_session), "__call__") as call: + call.return_value = session_service.RunSessionResponse() + client.run_session(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "config.session=session_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_run_session_field_headers_async(): + client = SessionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = session_service.RunSessionRequest() + + request.config.session = "session_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.run_session), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + session_service.RunSessionResponse() + ) + await client.run_session(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "config.session=session_value", + ) in kw["metadata"] + + +@pytest.mark.parametrize( + "request_type", + [ + session_service.BidiSessionClientMessage, + dict, + ], +) +def test_bidi_run_session(request_type, transport: str = "grpc"): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + requests = [request] + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.bidi_run_session), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = iter([session_service.BidiSessionServerMessage()]) + response = client.bidi_run_session(iter(requests)) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert next(args[0]) == request + + # Establish that the response is the type that we expect. + for message in response: + assert isinstance(message, session_service.BidiSessionServerMessage) + + +def test_bidi_run_session_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.bidi_run_session in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.bidi_run_session] = ( + mock_rpc + ) + request = [{}] + client.bidi_run_session(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.bidi_run_session(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_bidi_run_session_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SessionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.bidi_run_session + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.bidi_run_session + ] = mock_rpc + + request = [{}] + await client.bidi_run_session(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.bidi_run_session(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_bidi_run_session_async( + transport: str = "grpc_asyncio", + request_type=session_service.BidiSessionClientMessage, +): + client = SessionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + requests = [request] + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.bidi_run_session), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = mock.Mock(aio.StreamStreamCall, autospec=True) + call.return_value.read = mock.AsyncMock( + side_effect=[session_service.BidiSessionServerMessage()] + ) + response = await client.bidi_run_session(iter(requests)) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert next(args[0]) == request + + # Establish that the response is the type that we expect. + message = await response.read() + assert isinstance(message, session_service.BidiSessionServerMessage) + + +@pytest.mark.asyncio +async def test_bidi_run_session_async_from_dict(): + await test_bidi_run_session_async(request_type=dict) + + +def test_run_session_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.run_session in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.run_session] = mock_rpc + + request = {} + client.run_session(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.run_session(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_run_session_rest_required_fields( + request_type=session_service.RunSessionRequest, +): + transport_class = transports.SessionServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).run_session._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).run_session._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = session_service.RunSessionResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = session_service.RunSessionResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.run_session(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_run_session_rest_unset_required_fields(): + transport = transports.SessionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.run_session._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "config", + "inputs", + ) + ) + ) + + +def test_bidi_run_session_rest_no_http_options(): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = session_service.BidiSessionClientMessage() + requests = [request] + with pytest.raises(RuntimeError): + client.bidi_run_session(requests) + + +def test_bidi_run_session_rest_error(): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # Since a `google.api.http` annotation is required for using a rest transport + # method, this should error. + with pytest.raises(NotImplementedError) as not_implemented_error: + client.bidi_run_session({}) + assert "Method BidiRunSession is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SessionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SessionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SessionServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SessionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SessionServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SessionServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SessionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SessionServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SessionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SessionServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SessionServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SessionServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SessionServiceGrpcTransport, + transports.SessionServiceGrpcAsyncIOTransport, + transports.SessionServiceRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_kind_grpc(): + transport = SessionServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_run_session_empty_call_grpc(): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.run_session), "__call__") as call: + call.return_value = session_service.RunSessionResponse() + client.run_session(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = session_service.RunSessionRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = SessionServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = SessionServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_run_session_empty_call_grpc_asyncio(): + client = SessionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.run_session), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + session_service.RunSessionResponse() + ) + await client.run_session(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = session_service.RunSessionRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = SessionServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_run_session_rest_bad_request(request_type=session_service.RunSessionRequest): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "config": { + "session": "projects/sample1/locations/sample2/apps/sample3/sessions/sample4" + } + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.run_session(request) + + +@pytest.mark.parametrize( + "request_type", + [ + session_service.RunSessionRequest, + dict, + ], +) +def test_run_session_rest_call_success(request_type): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "config": { + "session": "projects/sample1/locations/sample2/apps/sample3/sessions/sample4" + } + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = session_service.RunSessionResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = session_service.RunSessionResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.run_session(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, session_service.RunSessionResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_run_session_rest_interceptors(null_interceptor): + transport = transports.SessionServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SessionServiceRestInterceptor(), + ) + client = SessionServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.SessionServiceRestInterceptor, "post_run_session" + ) as post, mock.patch.object( + transports.SessionServiceRestInterceptor, "post_run_session_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.SessionServiceRestInterceptor, "pre_run_session" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = session_service.RunSessionRequest.pb( + session_service.RunSessionRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = session_service.RunSessionResponse.to_json( + session_service.RunSessionResponse() + ) + req.return_value.content = return_value + + request = session_service.RunSessionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = session_service.RunSessionResponse() + post_with_metadata.return_value = session_service.RunSessionResponse(), metadata + + client.run_session( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_bidi_run_session_rest_error(): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + with pytest.raises(NotImplementedError) as not_implemented_error: + client.bidi_run_session({}) + assert "Method BidiRunSession is not available over REST transport" in str( + not_implemented_error.value + ) + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_location(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.GetLocationRequest, + dict, + ], +) +def test_get_location_rest(request_type): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_list_locations_rest_bad_request( + request_type=locations_pb2.ListLocationsRequest, +): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"name": "projects/sample1"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_locations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.ListLocationsRequest, + dict, + ], +) +def test_list_locations_rest(request_type): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_cancel_operation_rest_bad_request( + request_type=operations_pb2.CancelOperationRequest, +): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_rest_bad_request( + request_type=operations_pb2.DeleteOperationRequest, +): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_run_session_empty_call_rest(): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.run_session), "__call__") as call: + client.run_session(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = session_service.RunSessionRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SessionServiceGrpcTransport, + ) + + +def test_session_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SessionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_session_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.ces_v1beta.services.session_service.transports.SessionServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.SessionServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "run_session", + "bidi_run_session", + "get_location", + "list_locations", + "get_operation", + "cancel_operation", + "delete_operation", + "list_operations", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_session_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.ces_v1beta.services.session_service.transports.SessionServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SessionServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/ces", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +def test_session_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.ces_v1beta.services.session_service.transports.SessionServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SessionServiceTransport() + adc.assert_called_once() + + +def test_session_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + SessionServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/ces", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SessionServiceGrpcTransport, + transports.SessionServiceGrpcAsyncIOTransport, + ], +) +def test_session_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/ces", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SessionServiceGrpcTransport, + transports.SessionServiceGrpcAsyncIOTransport, + transports.SessionServiceRestTransport, + ], +) +def test_session_service_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.SessionServiceGrpcTransport, grpc_helpers), + (transports.SessionServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_session_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "ces.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/ces", + "https://www.googleapis.com/auth/cloud-platform", + ), + scopes=["1", "2"], + default_host="ces.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SessionServiceGrpcTransport, + transports.SessionServiceGrpcAsyncIOTransport, + ], +) +def test_session_service_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_session_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.SessionServiceRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_session_service_host_no_port(transport_name): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint="ces.googleapis.com"), + transport=transport_name, + ) + assert client.transport._host == ( + "ces.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://ces.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_session_service_host_with_port(transport_name): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="ces.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "ces.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://ces.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_session_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = SessionServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = SessionServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.run_session._session + session2 = client2.transport.run_session._session + assert session1 != session2 + session1 = client1.transport.bidi_run_session._session + session2 = client2.transport.bidi_run_session._session + assert session1 != session2 + + +def test_session_service_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SessionServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_session_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SessionServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.filterwarnings("ignore::FutureWarning") +@pytest.mark.parametrize( + "transport_class", + [ + transports.SessionServiceGrpcTransport, + transports.SessionServiceGrpcAsyncIOTransport, + ], +) +def test_session_service_transport_channel_mtls_with_client_cert_source( + transport_class, +): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.SessionServiceGrpcTransport, + transports.SessionServiceGrpcAsyncIOTransport, + ], +) +def test_session_service_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_agent_path(): + project = "squid" + location = "clam" + app = "whelk" + agent = "octopus" + expected = ( + "projects/{project}/locations/{location}/apps/{app}/agents/{agent}".format( + project=project, + location=location, + app=app, + agent=agent, + ) + ) + actual = SessionServiceClient.agent_path(project, location, app, agent) + assert expected == actual + + +def test_parse_agent_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "app": "cuttlefish", + "agent": "mussel", + } + path = SessionServiceClient.agent_path(**expected) + + # Check that the path construction is reversible. + actual = SessionServiceClient.parse_agent_path(path) + assert expected == actual + + +def test_session_path(): + project = "winkle" + location = "nautilus" + app = "scallop" + session = "abalone" + expected = ( + "projects/{project}/locations/{location}/apps/{app}/sessions/{session}".format( + project=project, + location=location, + app=app, + session=session, + ) + ) + actual = SessionServiceClient.session_path(project, location, app, session) + assert expected == actual + + +def test_parse_session_path(): + expected = { + "project": "squid", + "location": "clam", + "app": "whelk", + "session": "octopus", + } + path = SessionServiceClient.session_path(**expected) + + # Check that the path construction is reversible. + actual = SessionServiceClient.parse_session_path(path) + assert expected == actual + + +def test_tool_path(): + project = "oyster" + location = "nudibranch" + app = "cuttlefish" + tool = "mussel" + expected = "projects/{project}/locations/{location}/apps/{app}/tools/{tool}".format( + project=project, + location=location, + app=app, + tool=tool, + ) + actual = SessionServiceClient.tool_path(project, location, app, tool) + assert expected == actual + + +def test_parse_tool_path(): + expected = { + "project": "winkle", + "location": "nautilus", + "app": "scallop", + "tool": "abalone", + } + path = SessionServiceClient.tool_path(**expected) + + # Check that the path construction is reversible. + actual = SessionServiceClient.parse_tool_path(path) + assert expected == actual + + +def test_toolset_path(): + project = "squid" + location = "clam" + app = "whelk" + toolset = "octopus" + expected = ( + "projects/{project}/locations/{location}/apps/{app}/toolsets/{toolset}".format( + project=project, + location=location, + app=app, + toolset=toolset, + ) + ) + actual = SessionServiceClient.toolset_path(project, location, app, toolset) + assert expected == actual + + +def test_parse_toolset_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "app": "cuttlefish", + "toolset": "mussel", + } + path = SessionServiceClient.toolset_path(**expected) + + # Check that the path construction is reversible. + actual = SessionServiceClient.parse_toolset_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = SessionServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = SessionServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SessionServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = SessionServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = SessionServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SessionServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = SessionServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = SessionServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SessionServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format( + project=project, + ) + actual = SessionServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = SessionServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SessionServiceClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "oyster" + location = "nudibranch" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = SessionServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = SessionServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SessionServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.SessionServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.SessionServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = SessionServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_delete_operation(transport: str = "grpc"): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc_asyncio"): + client = SessionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_field_headers(): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_operation_field_headers_async(): + client = SessionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_delete_operation_from_dict(): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = SessionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc_asyncio"): + client = SessionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_cancel_operation_field_headers(): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = SessionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_cancel_operation_from_dict(): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = SessionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = SessionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_get_operation_field_headers(): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = SessionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_get_operation_from_dict(): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = SessionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = SessionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_list_operations_field_headers(): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = SessionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_list_operations_from_dict(): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = SessionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_locations(transport: str = "grpc"): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc_asyncio"): + client = SessionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_list_locations_field_headers(): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_locations_field_headers_async(): + client = SessionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_list_locations_from_dict(): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = SessionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_location(transport: str = "grpc"): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + response = client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + client = SessionServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_get_location_field_headers(): + client = SessionServiceClient(credentials=ga_credentials.AnonymousCredentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() + + client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations/abc", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_location_field_headers_async(): + client = SessionServiceAsyncClient(credentials=async_anonymous_credentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations/abc", + ) in kw["metadata"] + + +def test_get_location_from_dict(): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + response = client.get_location( + request={ + "name": "locations/abc", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_location_from_dict_async(): + client = SessionServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close_grpc(): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = SessionServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "rest", + "grpc", + ] + for transport in transports: + client = SessionServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (SessionServiceClient, transports.SessionServiceGrpcTransport), + (SessionServiceAsyncClient, transports.SessionServiceGrpcAsyncIOTransport), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/packages/google-cloud-ces/tests/unit/gapic/ces_v1beta/test_tool_service.py b/packages/google-cloud-ces/tests/unit/gapic/ces_v1beta/test_tool_service.py new file mode 100644 index 000000000000..4cb0cc403d4c --- /dev/null +++ b/packages/google-cloud-ces/tests/unit/gapic/ces_v1beta/test_tool_service.py @@ -0,0 +1,5106 @@ +# -*- coding: utf-8 -*- +# 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. +# +import os + +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import json +import math +from collections.abc import AsyncIterable, Iterable, Mapping, Sequence + +import grpc +import pytest +from google.api_core import api_core_version +from google.protobuf import json_format +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +import google.auth +import google.protobuf.struct_pb2 as struct_pb2 # type: ignore +from google.api_core import ( + client_options, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + path_template, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account + +from google.cloud.ces_v1beta.services.tool_service import ( + ToolServiceAsyncClient, + ToolServiceClient, + transports, +) +from google.cloud.ces_v1beta.types import schema, tool, tool_service, toolset_tool + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ToolServiceClient._get_default_mtls_endpoint(None) is None + assert ( + ToolServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + ) + assert ( + ToolServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + ToolServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + ToolServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ToolServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +def test__read_environment_variables(): + assert ToolServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert ToolServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert ToolServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with pytest.raises(ValueError) as excinfo: + ToolServiceClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + else: + assert ToolServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert ToolServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert ToolServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert ToolServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + ToolServiceClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert ToolServiceClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + + +def test_use_client_cert_effective(): + # Test case 1: Test when `should_use_client_cert` returns True. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch( + "google.auth.transport.mtls.should_use_client_cert", return_value=True + ): + assert ToolServiceClient._use_client_cert_effective() is True + + # Test case 2: Test when `should_use_client_cert` returns False. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should NOT be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch( + "google.auth.transport.mtls.should_use_client_cert", return_value=False + ): + assert ToolServiceClient._use_client_cert_effective() is False + + # Test case 3: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "true". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert ToolServiceClient._use_client_cert_effective() is True + + # Test case 4: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"} + ): + assert ToolServiceClient._use_client_cert_effective() is False + + # Test case 5: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "True". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "True"}): + assert ToolServiceClient._use_client_cert_effective() is True + + # Test case 6: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "False". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"} + ): + assert ToolServiceClient._use_client_cert_effective() is False + + # Test case 7: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "TRUE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "TRUE"}): + assert ToolServiceClient._use_client_cert_effective() is True + + # Test case 8: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "FALSE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"} + ): + assert ToolServiceClient._use_client_cert_effective() is False + + # Test case 9: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not set. + # In this case, the method should return False, which is the default value. + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, clear=True): + assert ToolServiceClient._use_client_cert_effective() is False + + # Test case 10: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should raise a ValueError as the environment variable must be either + # "true" or "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} + ): + with pytest.raises(ValueError): + ToolServiceClient._use_client_cert_effective() + + # Test case 11: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should return False as the environment variable is set to an invalid value. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} + ): + assert ToolServiceClient._use_client_cert_effective() is False + + # Test case 12: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is unset. Also, + # the GOOGLE_API_CONFIG environment variable is unset. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": ""}): + with mock.patch.dict(os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": ""}): + assert ToolServiceClient._use_client_cert_effective() is False + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert ToolServiceClient._get_client_cert_source(None, False) is None + assert ( + ToolServiceClient._get_client_cert_source(mock_provided_cert_source, False) + is None + ) + assert ( + ToolServiceClient._get_client_cert_source(mock_provided_cert_source, True) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + ToolServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + ToolServiceClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + ToolServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ToolServiceClient), +) +@mock.patch.object( + ToolServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ToolServiceAsyncClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = ToolServiceClient._DEFAULT_UNIVERSE + default_endpoint = ToolServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = ToolServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + ToolServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + ToolServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == ToolServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + ToolServiceClient._get_api_endpoint(None, None, default_universe, "auto") + == default_endpoint + ) + assert ( + ToolServiceClient._get_api_endpoint(None, None, default_universe, "always") + == ToolServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + ToolServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == ToolServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + ToolServiceClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + ToolServiceClient._get_api_endpoint(None, None, default_universe, "never") + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + ToolServiceClient._get_api_endpoint( + None, mock_client_cert_source, mock_universe, "auto" + ) + assert ( + str(excinfo.value) + == "mTLS is not supported in any universe other than googleapis.com." + ) + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert ( + ToolServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + ToolServiceClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + ToolServiceClient._get_universe_domain(None, None) + == ToolServiceClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + ToolServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize( + "error_code,cred_info_json,show_cred_info", + [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False), + ], +) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = ToolServiceClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + + +@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = ToolServiceClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (ToolServiceClient, "grpc"), + (ToolServiceAsyncClient, "grpc_asyncio"), + (ToolServiceClient, "rest"), + ], +) +def test_tool_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "ces.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://ces.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.ToolServiceGrpcTransport, "grpc"), + (transports.ToolServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ToolServiceRestTransport, "rest"), + ], +) +def test_tool_service_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (ToolServiceClient, "grpc"), + (ToolServiceAsyncClient, "grpc_asyncio"), + (ToolServiceClient, "rest"), + ], +) +def test_tool_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "ces.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://ces.googleapis.com" + ) + + +def test_tool_service_client_get_transport_class(): + transport = ToolServiceClient.get_transport_class() + available_transports = [ + transports.ToolServiceGrpcTransport, + transports.ToolServiceRestTransport, + ] + assert transport in available_transports + + transport = ToolServiceClient.get_transport_class("grpc") + assert transport == transports.ToolServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ToolServiceClient, transports.ToolServiceGrpcTransport, "grpc"), + ( + ToolServiceAsyncClient, + transports.ToolServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (ToolServiceClient, transports.ToolServiceRestTransport, "rest"), + ], +) +@mock.patch.object( + ToolServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ToolServiceClient), +) +@mock.patch.object( + ToolServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ToolServiceAsyncClient), +) +def test_tool_service_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(ToolServiceClient, "get_transport_class") as gtc: + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(ToolServiceClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (ToolServiceClient, transports.ToolServiceGrpcTransport, "grpc", "true"), + ( + ToolServiceAsyncClient, + transports.ToolServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (ToolServiceClient, transports.ToolServiceGrpcTransport, "grpc", "false"), + ( + ToolServiceAsyncClient, + transports.ToolServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + (ToolServiceClient, transports.ToolServiceRestTransport, "rest", "true"), + (ToolServiceClient, transports.ToolServiceRestTransport, "rest", "false"), + ], +) +@mock.patch.object( + ToolServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ToolServiceClient), +) +@mock.patch.object( + ToolServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ToolServiceAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_tool_service_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ToolServiceClient, ToolServiceAsyncClient]) +@mock.patch.object( + ToolServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ToolServiceClient) +) +@mock.patch.object( + ToolServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ToolServiceAsyncClient), +) +def test_tool_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset. + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source() + ) + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + +@pytest.mark.parametrize("client_class", [ToolServiceClient, ToolServiceAsyncClient]) +@mock.patch.object( + ToolServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ToolServiceClient), +) +@mock.patch.object( + ToolServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ToolServiceAsyncClient), +) +def test_tool_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = ToolServiceClient._DEFAULT_UNIVERSE + default_endpoint = ToolServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = ToolServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ToolServiceClient, transports.ToolServiceGrpcTransport, "grpc"), + ( + ToolServiceAsyncClient, + transports.ToolServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (ToolServiceClient, transports.ToolServiceRestTransport, "rest"), + ], +) +def test_tool_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + (ToolServiceClient, transports.ToolServiceGrpcTransport, "grpc", grpc_helpers), + ( + ToolServiceAsyncClient, + transports.ToolServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + (ToolServiceClient, transports.ToolServiceRestTransport, "rest", None), + ], +) +def test_tool_service_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_tool_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.ces_v1beta.services.tool_service.transports.ToolServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = ToolServiceClient(client_options={"api_endpoint": "squid.clam.whelk"}) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + (ToolServiceClient, transports.ToolServiceGrpcTransport, "grpc", grpc_helpers), + ( + ToolServiceAsyncClient, + transports.ToolServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_tool_service_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object(grpc_helpers, "create_channel") as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "ces.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + "https://www.googleapis.com/auth/ces", + "https://www.googleapis.com/auth/cloud-platform", + ), + scopes=None, + default_host="ces.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + tool_service.ExecuteToolRequest, + dict, + ], +) +def test_execute_tool(request_type, transport: str = "grpc"): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.execute_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = tool_service.ExecuteToolResponse( + tool="tool_value", + ) + response = client.execute_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = tool_service.ExecuteToolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, tool_service.ExecuteToolResponse) + + +def test_execute_tool_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = tool_service.ExecuteToolRequest( + tool="tool_value", + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.execute_tool), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.execute_tool(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tool_service.ExecuteToolRequest( + tool="tool_value", + parent="parent_value", + ) + + +def test_execute_tool_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.execute_tool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.execute_tool] = mock_rpc + request = {} + client.execute_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.execute_tool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_execute_tool_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ToolServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.execute_tool + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.execute_tool + ] = mock_rpc + + request = {} + await client.execute_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.execute_tool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_execute_tool_async( + transport: str = "grpc_asyncio", request_type=tool_service.ExecuteToolRequest +): + client = ToolServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.execute_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + tool_service.ExecuteToolResponse() + ) + response = await client.execute_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = tool_service.ExecuteToolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, tool_service.ExecuteToolResponse) + + +@pytest.mark.asyncio +async def test_execute_tool_async_from_dict(): + await test_execute_tool_async(request_type=dict) + + +def test_execute_tool_field_headers(): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tool_service.ExecuteToolRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.execute_tool), "__call__") as call: + call.return_value = tool_service.ExecuteToolResponse() + client.execute_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_execute_tool_field_headers_async(): + client = ToolServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tool_service.ExecuteToolRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.execute_tool), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + tool_service.ExecuteToolResponse() + ) + await client.execute_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.parametrize( + "request_type", + [ + tool_service.RetrieveToolSchemaRequest, + dict, + ], +) +def test_retrieve_tool_schema(request_type, transport: str = "grpc"): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_tool_schema), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = tool_service.RetrieveToolSchemaResponse( + tool="tool_value", + ) + response = client.retrieve_tool_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = tool_service.RetrieveToolSchemaRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, tool_service.RetrieveToolSchemaResponse) + + +def test_retrieve_tool_schema_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = tool_service.RetrieveToolSchemaRequest( + tool="tool_value", + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_tool_schema), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.retrieve_tool_schema(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tool_service.RetrieveToolSchemaRequest( + tool="tool_value", + parent="parent_value", + ) + + +def test_retrieve_tool_schema_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.retrieve_tool_schema in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.retrieve_tool_schema] = ( + mock_rpc + ) + request = {} + client.retrieve_tool_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.retrieve_tool_schema(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_retrieve_tool_schema_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ToolServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.retrieve_tool_schema + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.retrieve_tool_schema + ] = mock_rpc + + request = {} + await client.retrieve_tool_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.retrieve_tool_schema(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_retrieve_tool_schema_async( + transport: str = "grpc_asyncio", request_type=tool_service.RetrieveToolSchemaRequest +): + client = ToolServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_tool_schema), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + tool_service.RetrieveToolSchemaResponse() + ) + response = await client.retrieve_tool_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = tool_service.RetrieveToolSchemaRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, tool_service.RetrieveToolSchemaResponse) + + +@pytest.mark.asyncio +async def test_retrieve_tool_schema_async_from_dict(): + await test_retrieve_tool_schema_async(request_type=dict) + + +def test_retrieve_tool_schema_field_headers(): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tool_service.RetrieveToolSchemaRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_tool_schema), "__call__" + ) as call: + call.return_value = tool_service.RetrieveToolSchemaResponse() + client.retrieve_tool_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_retrieve_tool_schema_field_headers_async(): + client = ToolServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tool_service.RetrieveToolSchemaRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_tool_schema), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + tool_service.RetrieveToolSchemaResponse() + ) + await client.retrieve_tool_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.parametrize( + "request_type", + [ + tool_service.RetrieveToolsRequest, + dict, + ], +) +def test_retrieve_tools(request_type, transport: str = "grpc"): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.retrieve_tools), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = tool_service.RetrieveToolsResponse() + response = client.retrieve_tools(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = tool_service.RetrieveToolsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, tool_service.RetrieveToolsResponse) + + +def test_retrieve_tools_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = tool_service.RetrieveToolsRequest( + toolset="toolset_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.retrieve_tools), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.retrieve_tools(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == tool_service.RetrieveToolsRequest( + toolset="toolset_value", + ) + + +def test_retrieve_tools_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.retrieve_tools in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.retrieve_tools] = mock_rpc + request = {} + client.retrieve_tools(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.retrieve_tools(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_retrieve_tools_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = ToolServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.retrieve_tools + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.retrieve_tools + ] = mock_rpc + + request = {} + await client.retrieve_tools(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.retrieve_tools(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_retrieve_tools_async( + transport: str = "grpc_asyncio", request_type=tool_service.RetrieveToolsRequest +): + client = ToolServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.retrieve_tools), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + tool_service.RetrieveToolsResponse() + ) + response = await client.retrieve_tools(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = tool_service.RetrieveToolsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, tool_service.RetrieveToolsResponse) + + +@pytest.mark.asyncio +async def test_retrieve_tools_async_from_dict(): + await test_retrieve_tools_async(request_type=dict) + + +def test_retrieve_tools_field_headers(): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tool_service.RetrieveToolsRequest() + + request.toolset = "toolset_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.retrieve_tools), "__call__") as call: + call.return_value = tool_service.RetrieveToolsResponse() + client.retrieve_tools(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "toolset=toolset_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_retrieve_tools_field_headers_async(): + client = ToolServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = tool_service.RetrieveToolsRequest() + + request.toolset = "toolset_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.retrieve_tools), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + tool_service.RetrieveToolsResponse() + ) + await client.retrieve_tools(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "toolset=toolset_value", + ) in kw["metadata"] + + +def test_execute_tool_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.execute_tool in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.execute_tool] = mock_rpc + + request = {} + client.execute_tool(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.execute_tool(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_execute_tool_rest_required_fields( + request_type=tool_service.ExecuteToolRequest, +): + transport_class = transports.ToolServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).execute_tool._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).execute_tool._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = tool_service.ExecuteToolResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = tool_service.ExecuteToolResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.execute_tool(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_execute_tool_rest_unset_required_fields(): + transport = transports.ToolServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.execute_tool._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent",))) + + +def test_retrieve_tool_schema_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.retrieve_tool_schema in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.retrieve_tool_schema] = ( + mock_rpc + ) + + request = {} + client.retrieve_tool_schema(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.retrieve_tool_schema(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_retrieve_tool_schema_rest_required_fields( + request_type=tool_service.RetrieveToolSchemaRequest, +): + transport_class = transports.ToolServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).retrieve_tool_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).retrieve_tool_schema._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = tool_service.RetrieveToolSchemaResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = tool_service.RetrieveToolSchemaResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.retrieve_tool_schema(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_retrieve_tool_schema_rest_unset_required_fields(): + transport = transports.ToolServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.retrieve_tool_schema._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent",))) + + +def test_retrieve_tools_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.retrieve_tools in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.retrieve_tools] = mock_rpc + + request = {} + client.retrieve_tools(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.retrieve_tools(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_retrieve_tools_rest_required_fields( + request_type=tool_service.RetrieveToolsRequest, +): + transport_class = transports.ToolServiceRestTransport + + request_init = {} + request_init["toolset"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).retrieve_tools._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["toolset"] = "toolset_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).retrieve_tools._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "toolset" in jsonified_request + assert jsonified_request["toolset"] == "toolset_value" + + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = tool_service.RetrieveToolsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = tool_service.RetrieveToolsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.retrieve_tools(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_retrieve_tools_rest_unset_required_fields(): + transport = transports.ToolServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.retrieve_tools._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("toolset",))) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ToolServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ToolServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ToolServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ToolServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ToolServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ToolServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ToolServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ToolServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ToolServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ToolServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ToolServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ToolServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ToolServiceGrpcTransport, + transports.ToolServiceGrpcAsyncIOTransport, + transports.ToolServiceRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_kind_grpc(): + transport = ToolServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_execute_tool_empty_call_grpc(): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.execute_tool), "__call__") as call: + call.return_value = tool_service.ExecuteToolResponse() + client.execute_tool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tool_service.ExecuteToolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_retrieve_tool_schema_empty_call_grpc(): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_tool_schema), "__call__" + ) as call: + call.return_value = tool_service.RetrieveToolSchemaResponse() + client.retrieve_tool_schema(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tool_service.RetrieveToolSchemaRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_retrieve_tools_empty_call_grpc(): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.retrieve_tools), "__call__") as call: + call.return_value = tool_service.RetrieveToolsResponse() + client.retrieve_tools(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tool_service.RetrieveToolsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = ToolServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = ToolServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_execute_tool_empty_call_grpc_asyncio(): + client = ToolServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.execute_tool), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + tool_service.ExecuteToolResponse() + ) + await client.execute_tool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tool_service.ExecuteToolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_retrieve_tool_schema_empty_call_grpc_asyncio(): + client = ToolServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_tool_schema), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + tool_service.RetrieveToolSchemaResponse() + ) + await client.retrieve_tool_schema(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tool_service.RetrieveToolSchemaRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_retrieve_tools_empty_call_grpc_asyncio(): + client = ToolServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.retrieve_tools), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + tool_service.RetrieveToolsResponse() + ) + await client.retrieve_tools(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tool_service.RetrieveToolsRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = ToolServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_execute_tool_rest_bad_request(request_type=tool_service.ExecuteToolRequest): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.execute_tool(request) + + +@pytest.mark.parametrize( + "request_type", + [ + tool_service.ExecuteToolRequest, + dict, + ], +) +def test_execute_tool_rest_call_success(request_type): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = tool_service.ExecuteToolResponse( + tool="tool_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = tool_service.ExecuteToolResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.execute_tool(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, tool_service.ExecuteToolResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_execute_tool_rest_interceptors(null_interceptor): + transport = transports.ToolServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ToolServiceRestInterceptor(), + ) + client = ToolServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.ToolServiceRestInterceptor, "post_execute_tool" + ) as post, mock.patch.object( + transports.ToolServiceRestInterceptor, "post_execute_tool_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.ToolServiceRestInterceptor, "pre_execute_tool" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = tool_service.ExecuteToolRequest.pb( + tool_service.ExecuteToolRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = tool_service.ExecuteToolResponse.to_json( + tool_service.ExecuteToolResponse() + ) + req.return_value.content = return_value + + request = tool_service.ExecuteToolRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = tool_service.ExecuteToolResponse() + post_with_metadata.return_value = tool_service.ExecuteToolResponse(), metadata + + client.execute_tool( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_retrieve_tool_schema_rest_bad_request( + request_type=tool_service.RetrieveToolSchemaRequest, +): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.retrieve_tool_schema(request) + + +@pytest.mark.parametrize( + "request_type", + [ + tool_service.RetrieveToolSchemaRequest, + dict, + ], +) +def test_retrieve_tool_schema_rest_call_success(request_type): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/apps/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = tool_service.RetrieveToolSchemaResponse( + tool="tool_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = tool_service.RetrieveToolSchemaResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.retrieve_tool_schema(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, tool_service.RetrieveToolSchemaResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_retrieve_tool_schema_rest_interceptors(null_interceptor): + transport = transports.ToolServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ToolServiceRestInterceptor(), + ) + client = ToolServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.ToolServiceRestInterceptor, "post_retrieve_tool_schema" + ) as post, mock.patch.object( + transports.ToolServiceRestInterceptor, "post_retrieve_tool_schema_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.ToolServiceRestInterceptor, "pre_retrieve_tool_schema" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = tool_service.RetrieveToolSchemaRequest.pb( + tool_service.RetrieveToolSchemaRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = tool_service.RetrieveToolSchemaResponse.to_json( + tool_service.RetrieveToolSchemaResponse() + ) + req.return_value.content = return_value + + request = tool_service.RetrieveToolSchemaRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = tool_service.RetrieveToolSchemaResponse() + post_with_metadata.return_value = ( + tool_service.RetrieveToolSchemaResponse(), + metadata, + ) + + client.retrieve_tool_schema( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_retrieve_tools_rest_bad_request( + request_type=tool_service.RetrieveToolsRequest, +): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "toolset": "projects/sample1/locations/sample2/apps/sample3/toolsets/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.retrieve_tools(request) + + +@pytest.mark.parametrize( + "request_type", + [ + tool_service.RetrieveToolsRequest, + dict, + ], +) +def test_retrieve_tools_rest_call_success(request_type): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "toolset": "projects/sample1/locations/sample2/apps/sample3/toolsets/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = tool_service.RetrieveToolsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = tool_service.RetrieveToolsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.retrieve_tools(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, tool_service.RetrieveToolsResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_retrieve_tools_rest_interceptors(null_interceptor): + transport = transports.ToolServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ToolServiceRestInterceptor(), + ) + client = ToolServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.ToolServiceRestInterceptor, "post_retrieve_tools" + ) as post, mock.patch.object( + transports.ToolServiceRestInterceptor, "post_retrieve_tools_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.ToolServiceRestInterceptor, "pre_retrieve_tools" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = tool_service.RetrieveToolsRequest.pb( + tool_service.RetrieveToolsRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = tool_service.RetrieveToolsResponse.to_json( + tool_service.RetrieveToolsResponse() + ) + req.return_value.content = return_value + + request = tool_service.RetrieveToolsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = tool_service.RetrieveToolsResponse() + post_with_metadata.return_value = tool_service.RetrieveToolsResponse(), metadata + + client.retrieve_tools( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_location(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.GetLocationRequest, + dict, + ], +) +def test_get_location_rest(request_type): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_list_locations_rest_bad_request( + request_type=locations_pb2.ListLocationsRequest, +): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"name": "projects/sample1"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_locations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.ListLocationsRequest, + dict, + ], +) +def test_list_locations_rest(request_type): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_cancel_operation_rest_bad_request( + request_type=operations_pb2.CancelOperationRequest, +): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_rest_bad_request( + request_type=operations_pb2.DeleteOperationRequest, +): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_execute_tool_empty_call_rest(): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.execute_tool), "__call__") as call: + client.execute_tool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tool_service.ExecuteToolRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_retrieve_tool_schema_empty_call_rest(): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.retrieve_tool_schema), "__call__" + ) as call: + client.retrieve_tool_schema(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tool_service.RetrieveToolSchemaRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_retrieve_tools_empty_call_rest(): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.retrieve_tools), "__call__") as call: + client.retrieve_tools(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tool_service.RetrieveToolsRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ToolServiceGrpcTransport, + ) + + +def test_tool_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ToolServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_tool_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.ces_v1beta.services.tool_service.transports.ToolServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.ToolServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "execute_tool", + "retrieve_tool_schema", + "retrieve_tools", + "get_location", + "list_locations", + "get_operation", + "cancel_operation", + "delete_operation", + "list_operations", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_tool_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.ces_v1beta.services.tool_service.transports.ToolServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ToolServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/ces", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +def test_tool_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.ces_v1beta.services.tool_service.transports.ToolServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ToolServiceTransport() + adc.assert_called_once() + + +def test_tool_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ToolServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/ces", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ToolServiceGrpcTransport, + transports.ToolServiceGrpcAsyncIOTransport, + ], +) +def test_tool_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/ces", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ToolServiceGrpcTransport, + transports.ToolServiceGrpcAsyncIOTransport, + transports.ToolServiceRestTransport, + ], +) +def test_tool_service_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ToolServiceGrpcTransport, grpc_helpers), + (transports.ToolServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_tool_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "ces.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/ces", + "https://www.googleapis.com/auth/cloud-platform", + ), + scopes=["1", "2"], + default_host="ces.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.ToolServiceGrpcTransport, transports.ToolServiceGrpcAsyncIOTransport], +) +def test_tool_service_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_tool_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.ToolServiceRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_tool_service_host_no_port(transport_name): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint="ces.googleapis.com"), + transport=transport_name, + ) + assert client.transport._host == ( + "ces.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://ces.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_tool_service_host_with_port(transport_name): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="ces.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "ces.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://ces.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_tool_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ToolServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ToolServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.execute_tool._session + session2 = client2.transport.execute_tool._session + assert session1 != session2 + session1 = client1.transport.retrieve_tool_schema._session + session2 = client2.transport.retrieve_tool_schema._session + assert session1 != session2 + session1 = client1.transport.retrieve_tools._session + session2 = client2.transport.retrieve_tools._session + assert session1 != session2 + + +def test_tool_service_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ToolServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_tool_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ToolServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.filterwarnings("ignore::FutureWarning") +@pytest.mark.parametrize( + "transport_class", + [transports.ToolServiceGrpcTransport, transports.ToolServiceGrpcAsyncIOTransport], +) +def test_tool_service_transport_channel_mtls_with_client_cert_source(transport_class): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [transports.ToolServiceGrpcTransport, transports.ToolServiceGrpcAsyncIOTransport], +) +def test_tool_service_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_app_path(): + project = "squid" + location = "clam" + app = "whelk" + expected = "projects/{project}/locations/{location}/apps/{app}".format( + project=project, + location=location, + app=app, + ) + actual = ToolServiceClient.app_path(project, location, app) + assert expected == actual + + +def test_parse_app_path(): + expected = { + "project": "octopus", + "location": "oyster", + "app": "nudibranch", + } + path = ToolServiceClient.app_path(**expected) + + # Check that the path construction is reversible. + actual = ToolServiceClient.parse_app_path(path) + assert expected == actual + + +def test_secret_version_path(): + project = "cuttlefish" + secret = "mussel" + secret_version = "winkle" + expected = "projects/{project}/secrets/{secret}/versions/{secret_version}".format( + project=project, + secret=secret, + secret_version=secret_version, + ) + actual = ToolServiceClient.secret_version_path(project, secret, secret_version) + assert expected == actual + + +def test_parse_secret_version_path(): + expected = { + "project": "nautilus", + "secret": "scallop", + "secret_version": "abalone", + } + path = ToolServiceClient.secret_version_path(**expected) + + # Check that the path construction is reversible. + actual = ToolServiceClient.parse_secret_version_path(path) + assert expected == actual + + +def test_service_path(): + project = "squid" + location = "clam" + namespace = "whelk" + service = "octopus" + expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format( + project=project, + location=location, + namespace=namespace, + service=service, + ) + actual = ToolServiceClient.service_path(project, location, namespace, service) + assert expected == actual + + +def test_parse_service_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "namespace": "cuttlefish", + "service": "mussel", + } + path = ToolServiceClient.service_path(**expected) + + # Check that the path construction is reversible. + actual = ToolServiceClient.parse_service_path(path) + assert expected == actual + + +def test_tool_path(): + project = "winkle" + location = "nautilus" + app = "scallop" + tool = "abalone" + expected = "projects/{project}/locations/{location}/apps/{app}/tools/{tool}".format( + project=project, + location=location, + app=app, + tool=tool, + ) + actual = ToolServiceClient.tool_path(project, location, app, tool) + assert expected == actual + + +def test_parse_tool_path(): + expected = { + "project": "squid", + "location": "clam", + "app": "whelk", + "tool": "octopus", + } + path = ToolServiceClient.tool_path(**expected) + + # Check that the path construction is reversible. + actual = ToolServiceClient.parse_tool_path(path) + assert expected == actual + + +def test_toolset_path(): + project = "oyster" + location = "nudibranch" + app = "cuttlefish" + toolset = "mussel" + expected = ( + "projects/{project}/locations/{location}/apps/{app}/toolsets/{toolset}".format( + project=project, + location=location, + app=app, + toolset=toolset, + ) + ) + actual = ToolServiceClient.toolset_path(project, location, app, toolset) + assert expected == actual + + +def test_parse_toolset_path(): + expected = { + "project": "winkle", + "location": "nautilus", + "app": "scallop", + "toolset": "abalone", + } + path = ToolServiceClient.toolset_path(**expected) + + # Check that the path construction is reversible. + actual = ToolServiceClient.parse_toolset_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = ToolServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = ToolServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ToolServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = ToolServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = ToolServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ToolServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = ToolServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = ToolServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ToolServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format( + project=project, + ) + actual = ToolServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = ToolServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ToolServiceClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = ToolServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = ToolServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ToolServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.ToolServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.ToolServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = ToolServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_delete_operation(transport: str = "grpc"): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc_asyncio"): + client = ToolServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_field_headers(): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_operation_field_headers_async(): + client = ToolServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_delete_operation_from_dict(): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = ToolServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc_asyncio"): + client = ToolServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_cancel_operation_field_headers(): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = ToolServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_cancel_operation_from_dict(): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = ToolServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = ToolServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_get_operation_field_headers(): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = ToolServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_get_operation_from_dict(): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = ToolServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = ToolServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_list_operations_field_headers(): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = ToolServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_list_operations_from_dict(): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = ToolServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_locations(transport: str = "grpc"): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc_asyncio"): + client = ToolServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_list_locations_field_headers(): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_locations_field_headers_async(): + client = ToolServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_list_locations_from_dict(): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = ToolServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_location(transport: str = "grpc"): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + response = client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + client = ToolServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_get_location_field_headers(): + client = ToolServiceClient(credentials=ga_credentials.AnonymousCredentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() + + client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations/abc", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_location_field_headers_async(): + client = ToolServiceAsyncClient(credentials=async_anonymous_credentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations/abc", + ) in kw["metadata"] + + +def test_get_location_from_dict(): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + response = client.get_location( + request={ + "name": "locations/abc", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_location_from_dict_async(): + client = ToolServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close_grpc(): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = ToolServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "rest", + "grpc", + ] + for transport in transports: + client = ToolServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (ToolServiceClient, transports.ToolServiceGrpcTransport), + (ToolServiceAsyncClient, transports.ToolServiceGrpcAsyncIOTransport), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/packages/google-cloud-ces/tests/unit/gapic/ces_v1beta/test_widget_service.py b/packages/google-cloud-ces/tests/unit/gapic/ces_v1beta/test_widget_service.py new file mode 100644 index 000000000000..1042d35bb4c3 --- /dev/null +++ b/packages/google-cloud-ces/tests/unit/gapic/ces_v1beta/test_widget_service.py @@ -0,0 +1,3982 @@ +# -*- coding: utf-8 -*- +# 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. +# +import os + +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import json +import math +from collections.abc import AsyncIterable, Iterable, Mapping, Sequence + +import grpc +import pytest +from google.api_core import api_core_version +from google.protobuf import json_format +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +import google.auth +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.api_core import ( + client_options, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + path_template, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account + +from google.cloud.ces_v1beta.services.widget_service import ( + WidgetServiceAsyncClient, + WidgetServiceClient, + transports, +) +from google.cloud.ces_v1beta.types import widget_service + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert WidgetServiceClient._get_default_mtls_endpoint(None) is None + assert ( + WidgetServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + WidgetServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + WidgetServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + WidgetServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + WidgetServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + ) + + +def test__read_environment_variables(): + assert WidgetServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert WidgetServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert WidgetServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with pytest.raises(ValueError) as excinfo: + WidgetServiceClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + else: + assert WidgetServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert WidgetServiceClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert WidgetServiceClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert WidgetServiceClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + WidgetServiceClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert WidgetServiceClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + + +def test_use_client_cert_effective(): + # Test case 1: Test when `should_use_client_cert` returns True. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch( + "google.auth.transport.mtls.should_use_client_cert", return_value=True + ): + assert WidgetServiceClient._use_client_cert_effective() is True + + # Test case 2: Test when `should_use_client_cert` returns False. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should NOT be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch( + "google.auth.transport.mtls.should_use_client_cert", return_value=False + ): + assert WidgetServiceClient._use_client_cert_effective() is False + + # Test case 3: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "true". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert WidgetServiceClient._use_client_cert_effective() is True + + # Test case 4: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"} + ): + assert WidgetServiceClient._use_client_cert_effective() is False + + # Test case 5: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "True". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "True"}): + assert WidgetServiceClient._use_client_cert_effective() is True + + # Test case 6: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "False". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"} + ): + assert WidgetServiceClient._use_client_cert_effective() is False + + # Test case 7: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "TRUE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "TRUE"}): + assert WidgetServiceClient._use_client_cert_effective() is True + + # Test case 8: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "FALSE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"} + ): + assert WidgetServiceClient._use_client_cert_effective() is False + + # Test case 9: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not set. + # In this case, the method should return False, which is the default value. + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, clear=True): + assert WidgetServiceClient._use_client_cert_effective() is False + + # Test case 10: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should raise a ValueError as the environment variable must be either + # "true" or "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} + ): + with pytest.raises(ValueError): + WidgetServiceClient._use_client_cert_effective() + + # Test case 11: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should return False as the environment variable is set to an invalid value. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} + ): + assert WidgetServiceClient._use_client_cert_effective() is False + + # Test case 12: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is unset. Also, + # the GOOGLE_API_CONFIG environment variable is unset. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": ""}): + with mock.patch.dict(os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": ""}): + assert WidgetServiceClient._use_client_cert_effective() is False + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert WidgetServiceClient._get_client_cert_source(None, False) is None + assert ( + WidgetServiceClient._get_client_cert_source(mock_provided_cert_source, False) + is None + ) + assert ( + WidgetServiceClient._get_client_cert_source(mock_provided_cert_source, True) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + WidgetServiceClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + WidgetServiceClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + WidgetServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(WidgetServiceClient), +) +@mock.patch.object( + WidgetServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(WidgetServiceAsyncClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = WidgetServiceClient._DEFAULT_UNIVERSE + default_endpoint = WidgetServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = WidgetServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + WidgetServiceClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + WidgetServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == WidgetServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + WidgetServiceClient._get_api_endpoint(None, None, default_universe, "auto") + == default_endpoint + ) + assert ( + WidgetServiceClient._get_api_endpoint(None, None, default_universe, "always") + == WidgetServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + WidgetServiceClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == WidgetServiceClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + WidgetServiceClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + WidgetServiceClient._get_api_endpoint(None, None, default_universe, "never") + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + WidgetServiceClient._get_api_endpoint( + None, mock_client_cert_source, mock_universe, "auto" + ) + assert ( + str(excinfo.value) + == "mTLS is not supported in any universe other than googleapis.com." + ) + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert ( + WidgetServiceClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + WidgetServiceClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + WidgetServiceClient._get_universe_domain(None, None) + == WidgetServiceClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + WidgetServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize( + "error_code,cred_info_json,show_cred_info", + [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False), + ], +) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = WidgetServiceClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + + +@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = WidgetServiceClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (WidgetServiceClient, "grpc"), + (WidgetServiceAsyncClient, "grpc_asyncio"), + (WidgetServiceClient, "rest"), + ], +) +def test_widget_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "ces.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://ces.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.WidgetServiceGrpcTransport, "grpc"), + (transports.WidgetServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.WidgetServiceRestTransport, "rest"), + ], +) +def test_widget_service_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (WidgetServiceClient, "grpc"), + (WidgetServiceAsyncClient, "grpc_asyncio"), + (WidgetServiceClient, "rest"), + ], +) +def test_widget_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "ces.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://ces.googleapis.com" + ) + + +def test_widget_service_client_get_transport_class(): + transport = WidgetServiceClient.get_transport_class() + available_transports = [ + transports.WidgetServiceGrpcTransport, + transports.WidgetServiceRestTransport, + ] + assert transport in available_transports + + transport = WidgetServiceClient.get_transport_class("grpc") + assert transport == transports.WidgetServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (WidgetServiceClient, transports.WidgetServiceGrpcTransport, "grpc"), + ( + WidgetServiceAsyncClient, + transports.WidgetServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (WidgetServiceClient, transports.WidgetServiceRestTransport, "rest"), + ], +) +@mock.patch.object( + WidgetServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(WidgetServiceClient), +) +@mock.patch.object( + WidgetServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(WidgetServiceAsyncClient), +) +def test_widget_service_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(WidgetServiceClient, "get_transport_class") as gtc: + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(WidgetServiceClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (WidgetServiceClient, transports.WidgetServiceGrpcTransport, "grpc", "true"), + ( + WidgetServiceAsyncClient, + transports.WidgetServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (WidgetServiceClient, transports.WidgetServiceGrpcTransport, "grpc", "false"), + ( + WidgetServiceAsyncClient, + transports.WidgetServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + (WidgetServiceClient, transports.WidgetServiceRestTransport, "rest", "true"), + (WidgetServiceClient, transports.WidgetServiceRestTransport, "rest", "false"), + ], +) +@mock.patch.object( + WidgetServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(WidgetServiceClient), +) +@mock.patch.object( + WidgetServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(WidgetServiceAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_widget_service_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class", [WidgetServiceClient, WidgetServiceAsyncClient] +) +@mock.patch.object( + WidgetServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(WidgetServiceClient), +) +@mock.patch.object( + WidgetServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(WidgetServiceAsyncClient), +) +def test_widget_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported". + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset. + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, + api_endpoint=mock_api_endpoint, + ) + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source(options) + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is expected_cert_source + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + api_endpoint, cert_source = ( + client_class.get_mtls_endpoint_and_cert_source() + ) + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + +@pytest.mark.parametrize( + "client_class", [WidgetServiceClient, WidgetServiceAsyncClient] +) +@mock.patch.object( + WidgetServiceClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(WidgetServiceClient), +) +@mock.patch.object( + WidgetServiceAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(WidgetServiceAsyncClient), +) +def test_widget_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = WidgetServiceClient._DEFAULT_UNIVERSE + default_endpoint = WidgetServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = WidgetServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (WidgetServiceClient, transports.WidgetServiceGrpcTransport, "grpc"), + ( + WidgetServiceAsyncClient, + transports.WidgetServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (WidgetServiceClient, transports.WidgetServiceRestTransport, "rest"), + ], +) +def test_widget_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + WidgetServiceClient, + transports.WidgetServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + WidgetServiceAsyncClient, + transports.WidgetServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + (WidgetServiceClient, transports.WidgetServiceRestTransport, "rest", None), + ], +) +def test_widget_service_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_widget_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.ces_v1beta.services.widget_service.transports.WidgetServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = WidgetServiceClient( + client_options={"api_endpoint": "squid.clam.whelk"} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + WidgetServiceClient, + transports.WidgetServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + WidgetServiceAsyncClient, + transports.WidgetServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_widget_service_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object(grpc_helpers, "create_channel") as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "ces.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + "https://www.googleapis.com/auth/ces", + "https://www.googleapis.com/auth/cloud-platform", + ), + scopes=None, + default_host="ces.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + widget_service.GenerateChatTokenRequest, + dict, + ], +) +def test_generate_chat_token(request_type, transport: str = "grpc"): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_chat_token), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = widget_service.GenerateChatTokenResponse( + chat_token="chat_token_value", + ) + response = client.generate_chat_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = widget_service.GenerateChatTokenRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, widget_service.GenerateChatTokenResponse) + assert response.chat_token == "chat_token_value" + + +def test_generate_chat_token_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = widget_service.GenerateChatTokenRequest( + name="name_value", + deployment="deployment_value", + recaptcha_token="recaptcha_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_chat_token), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.generate_chat_token(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == widget_service.GenerateChatTokenRequest( + name="name_value", + deployment="deployment_value", + recaptcha_token="recaptcha_token_value", + ) + + +def test_generate_chat_token_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.generate_chat_token in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.generate_chat_token] = ( + mock_rpc + ) + request = {} + client.generate_chat_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.generate_chat_token(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_generate_chat_token_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = WidgetServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.generate_chat_token + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.generate_chat_token + ] = mock_rpc + + request = {} + await client.generate_chat_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.generate_chat_token(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_generate_chat_token_async( + transport: str = "grpc_asyncio", + request_type=widget_service.GenerateChatTokenRequest, +): + client = WidgetServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_chat_token), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + widget_service.GenerateChatTokenResponse( + chat_token="chat_token_value", + ) + ) + response = await client.generate_chat_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = widget_service.GenerateChatTokenRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, widget_service.GenerateChatTokenResponse) + assert response.chat_token == "chat_token_value" + + +@pytest.mark.asyncio +async def test_generate_chat_token_async_from_dict(): + await test_generate_chat_token_async(request_type=dict) + + +def test_generate_chat_token_field_headers(): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = widget_service.GenerateChatTokenRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_chat_token), "__call__" + ) as call: + call.return_value = widget_service.GenerateChatTokenResponse() + client.generate_chat_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_generate_chat_token_field_headers_async(): + client = WidgetServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = widget_service.GenerateChatTokenRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_chat_token), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + widget_service.GenerateChatTokenResponse() + ) + await client.generate_chat_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_generate_chat_token_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.generate_chat_token in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.generate_chat_token] = ( + mock_rpc + ) + + request = {} + client.generate_chat_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.generate_chat_token(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_generate_chat_token_rest_required_fields( + request_type=widget_service.GenerateChatTokenRequest, +): + transport_class = transports.WidgetServiceRestTransport + + request_init = {} + request_init["name"] = "" + request_init["deployment"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).generate_chat_token._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + jsonified_request["deployment"] = "deployment_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).generate_chat_token._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + assert "deployment" in jsonified_request + assert jsonified_request["deployment"] == "deployment_value" + + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = widget_service.GenerateChatTokenResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = widget_service.GenerateChatTokenResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.generate_chat_token(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_generate_chat_token_rest_unset_required_fields(): + transport = transports.WidgetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.generate_chat_token._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "name", + "deployment", + ) + ) + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.WidgetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.WidgetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WidgetServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.WidgetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = WidgetServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = WidgetServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.WidgetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WidgetServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.WidgetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = WidgetServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.WidgetServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.WidgetServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.WidgetServiceGrpcTransport, + transports.WidgetServiceGrpcAsyncIOTransport, + transports.WidgetServiceRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_kind_grpc(): + transport = WidgetServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_generate_chat_token_empty_call_grpc(): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_chat_token), "__call__" + ) as call: + call.return_value = widget_service.GenerateChatTokenResponse() + client.generate_chat_token(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = widget_service.GenerateChatTokenRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = WidgetServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = WidgetServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_generate_chat_token_empty_call_grpc_asyncio(): + client = WidgetServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_chat_token), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + widget_service.GenerateChatTokenResponse( + chat_token="chat_token_value", + ) + ) + await client.generate_chat_token(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = widget_service.GenerateChatTokenRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = WidgetServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_generate_chat_token_rest_bad_request( + request_type=widget_service.GenerateChatTokenRequest, +): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/sessions/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.generate_chat_token(request) + + +@pytest.mark.parametrize( + "request_type", + [ + widget_service.GenerateChatTokenRequest, + dict, + ], +) +def test_generate_chat_token_rest_call_success(request_type): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/apps/sample3/sessions/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = widget_service.GenerateChatTokenResponse( + chat_token="chat_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = widget_service.GenerateChatTokenResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.generate_chat_token(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, widget_service.GenerateChatTokenResponse) + assert response.chat_token == "chat_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_generate_chat_token_rest_interceptors(null_interceptor): + transport = transports.WidgetServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WidgetServiceRestInterceptor(), + ) + client = WidgetServiceClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.WidgetServiceRestInterceptor, "post_generate_chat_token" + ) as post, mock.patch.object( + transports.WidgetServiceRestInterceptor, + "post_generate_chat_token_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.WidgetServiceRestInterceptor, "pre_generate_chat_token" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = widget_service.GenerateChatTokenRequest.pb( + widget_service.GenerateChatTokenRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = widget_service.GenerateChatTokenResponse.to_json( + widget_service.GenerateChatTokenResponse() + ) + req.return_value.content = return_value + + request = widget_service.GenerateChatTokenRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = widget_service.GenerateChatTokenResponse() + post_with_metadata.return_value = ( + widget_service.GenerateChatTokenResponse(), + metadata, + ) + + client.generate_chat_token( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_location(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.GetLocationRequest, + dict, + ], +) +def test_get_location_rest(request_type): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_list_locations_rest_bad_request( + request_type=locations_pb2.ListLocationsRequest, +): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({"name": "projects/sample1"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_locations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.ListLocationsRequest, + dict, + ], +) +def test_list_locations_rest(request_type): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_cancel_operation_rest_bad_request( + request_type=operations_pb2.CancelOperationRequest, +): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_rest_bad_request( + request_type=operations_pb2.DeleteOperationRequest, +): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.delete_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.DeleteOperationRequest, + dict, + ], +) +def test_delete_operation_rest(request_type): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = "{}" + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, +): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.ListOperationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_generate_chat_token_empty_call_rest(): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_chat_token), "__call__" + ) as call: + client.generate_chat_token(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = widget_service.GenerateChatTokenRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.WidgetServiceGrpcTransport, + ) + + +def test_widget_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.WidgetServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_widget_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.ces_v1beta.services.widget_service.transports.WidgetServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.WidgetServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "generate_chat_token", + "get_location", + "list_locations", + "get_operation", + "cancel_operation", + "delete_operation", + "list_operations", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_widget_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.ces_v1beta.services.widget_service.transports.WidgetServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.WidgetServiceTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/ces", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +def test_widget_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.ces_v1beta.services.widget_service.transports.WidgetServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.WidgetServiceTransport() + adc.assert_called_once() + + +def test_widget_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + WidgetServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/ces", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.WidgetServiceGrpcTransport, + transports.WidgetServiceGrpcAsyncIOTransport, + ], +) +def test_widget_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/ces", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.WidgetServiceGrpcTransport, + transports.WidgetServiceGrpcAsyncIOTransport, + transports.WidgetServiceRestTransport, + ], +) +def test_widget_service_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.WidgetServiceGrpcTransport, grpc_helpers), + (transports.WidgetServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_widget_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "ces.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/ces", + "https://www.googleapis.com/auth/cloud-platform", + ), + scopes=["1", "2"], + default_host="ces.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.WidgetServiceGrpcTransport, + transports.WidgetServiceGrpcAsyncIOTransport, + ], +) +def test_widget_service_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_widget_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.WidgetServiceRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_widget_service_host_no_port(transport_name): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint="ces.googleapis.com"), + transport=transport_name, + ) + assert client.transport._host == ( + "ces.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://ces.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_widget_service_host_with_port(transport_name): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="ces.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "ces.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://ces.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_widget_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = WidgetServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = WidgetServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.generate_chat_token._session + session2 = client2.transport.generate_chat_token._session + assert session1 != session2 + + +def test_widget_service_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.WidgetServiceGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_widget_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.WidgetServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.filterwarnings("ignore::FutureWarning") +@pytest.mark.parametrize( + "transport_class", + [ + transports.WidgetServiceGrpcTransport, + transports.WidgetServiceGrpcAsyncIOTransport, + ], +) +def test_widget_service_transport_channel_mtls_with_client_cert_source(transport_class): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.WidgetServiceGrpcTransport, + transports.WidgetServiceGrpcAsyncIOTransport, + ], +) +def test_widget_service_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_deployment_path(): + project = "squid" + location = "clam" + app = "whelk" + deployment = "octopus" + expected = "projects/{project}/locations/{location}/apps/{app}/deployments/{deployment}".format( + project=project, + location=location, + app=app, + deployment=deployment, + ) + actual = WidgetServiceClient.deployment_path(project, location, app, deployment) + assert expected == actual + + +def test_parse_deployment_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "app": "cuttlefish", + "deployment": "mussel", + } + path = WidgetServiceClient.deployment_path(**expected) + + # Check that the path construction is reversible. + actual = WidgetServiceClient.parse_deployment_path(path) + assert expected == actual + + +def test_session_path(): + project = "winkle" + location = "nautilus" + app = "scallop" + session = "abalone" + expected = ( + "projects/{project}/locations/{location}/apps/{app}/sessions/{session}".format( + project=project, + location=location, + app=app, + session=session, + ) + ) + actual = WidgetServiceClient.session_path(project, location, app, session) + assert expected == actual + + +def test_parse_session_path(): + expected = { + "project": "squid", + "location": "clam", + "app": "whelk", + "session": "octopus", + } + path = WidgetServiceClient.session_path(**expected) + + # Check that the path construction is reversible. + actual = WidgetServiceClient.parse_session_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "oyster" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = WidgetServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nudibranch", + } + path = WidgetServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = WidgetServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "cuttlefish" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = WidgetServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "mussel", + } + path = WidgetServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = WidgetServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "winkle" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = WidgetServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nautilus", + } + path = WidgetServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = WidgetServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "scallop" + expected = "projects/{project}".format( + project=project, + ) + actual = WidgetServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "abalone", + } + path = WidgetServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = WidgetServiceClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = WidgetServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = WidgetServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = WidgetServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.WidgetServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.WidgetServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = WidgetServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_delete_operation(transport: str = "grpc"): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc_asyncio"): + client = WidgetServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_field_headers(): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_operation_field_headers_async(): + client = WidgetServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_delete_operation_from_dict(): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = WidgetServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc_asyncio"): + client = WidgetServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_cancel_operation_field_headers(): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = WidgetServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_cancel_operation_from_dict(): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = WidgetServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_operation(transport: str = "grpc"): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = WidgetServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_get_operation_field_headers(): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = WidgetServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_get_operation_from_dict(): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = WidgetServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_operations(transport: str = "grpc"): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc_asyncio"): + client = WidgetServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.ListOperationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_list_operations_field_headers(): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() + + client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = WidgetServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.ListOperationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_list_operations_from_dict(): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = WidgetServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_locations(transport: str = "grpc"): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc_asyncio"): + client = WidgetServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_list_locations_field_headers(): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_locations_field_headers_async(): + client = WidgetServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_list_locations_from_dict(): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = WidgetServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_location(transport: str = "grpc"): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + response = client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + client = WidgetServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_get_location_field_headers(): + client = WidgetServiceClient(credentials=ga_credentials.AnonymousCredentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() + + client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations/abc", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_location_field_headers_async(): + client = WidgetServiceAsyncClient(credentials=async_anonymous_credentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations/abc", + ) in kw["metadata"] + + +def test_get_location_from_dict(): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + response = client.get_location( + request={ + "name": "locations/abc", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_location_from_dict_async(): + client = WidgetServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close_grpc(): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = WidgetServiceAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + with mock.patch.object( + type(getattr(client.transport, "_grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "rest", + "grpc", + ] + for transport in transports: + client = WidgetServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (WidgetServiceClient, transports.WidgetServiceGrpcTransport), + (WidgetServiceAsyncClient, transports.WidgetServiceGrpcAsyncIOTransport), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + )