diff --git a/.librarian/state.yaml b/.librarian/state.yaml index 63defdf01256..e959e45436b6 100644 --- a/.librarian/state.yaml +++ b/.librarian/state.yaml @@ -53,7 +53,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-ai-generativelanguage version: 0.9.0 - last_generated_commit: 3322511885371d2b2253f209ccc3aa60d4100cfd + last_generated_commit: ef6a532bfd9ab7a944bdedd64c69a2b4042db58b apis: - path: google/ai/generativelanguage/v1 service_config: generativelanguage_v1.yaml @@ -134,7 +134,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-apps-chat version: 0.4.0 - last_generated_commit: e8365a7f88fabe8717cb8322b8ce784b03b6daea + last_generated_commit: ef6a532bfd9ab7a944bdedd64c69a2b4042db58b apis: - path: google/chat/v1 service_config: chat_v1.yaml @@ -293,7 +293,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-alloydb version: 0.6.0 - last_generated_commit: effe5c4fa816021e724ca856d5640f2e55b14a8b + last_generated_commit: ef6a532bfd9ab7a944bdedd64c69a2b4042db58b apis: - path: google/cloud/alloydb/v1beta service_config: alloydb_v1beta.yaml @@ -473,7 +473,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-artifact-registry version: 1.18.0 - last_generated_commit: 535d161c24965e9ed1a0b27032cc1c8b4beab818 + last_generated_commit: ef6a532bfd9ab7a944bdedd64c69a2b4042db58b apis: - path: google/devtools/artifactregistry/v1 service_config: artifactregistry_v1.yaml @@ -990,7 +990,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-build version: 3.34.0 - last_generated_commit: 535d161c24965e9ed1a0b27032cc1c8b4beab818 + last_generated_commit: ef6a532bfd9ab7a944bdedd64c69a2b4042db58b apis: - path: google/devtools/cloudbuild/v1 service_config: cloudbuild_v1.yaml @@ -1344,7 +1344,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-databasecenter version: 0.1.0 - last_generated_commit: 9a665b700840373e253db5af289d7df2a4fb41b9 + last_generated_commit: ef6a532bfd9ab7a944bdedd64c69a2b4042db58b apis: - path: google/cloud/databasecenter/v1beta service_config: databasecenter_v1beta.yaml @@ -1576,7 +1576,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-dialogflow version: 2.44.0 - last_generated_commit: c2db528a3e4d12b95666c719ee0db30a3d4c78ad + last_generated_commit: ef6a532bfd9ab7a944bdedd64c69a2b4042db58b apis: - path: google/cloud/dialogflow/v2beta1 service_config: dialogflow_v2beta1.yaml @@ -1595,7 +1595,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-dialogflow-cx version: 2.1.0 - last_generated_commit: c2db528a3e4d12b95666c719ee0db30a3d4c78ad + last_generated_commit: ef6a532bfd9ab7a944bdedd64c69a2b4042db58b apis: - path: google/cloud/dialogflow/cx/v3 service_config: dialogflow_v3.yaml @@ -1635,7 +1635,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-dlp version: 3.33.0 - last_generated_commit: 3322511885371d2b2253f209ccc3aa60d4100cfd + last_generated_commit: ef6a532bfd9ab7a944bdedd64c69a2b4042db58b apis: - path: google/privacy/dlp/v2 service_config: dlp_v2.yaml @@ -1879,7 +1879,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-geminidataanalytics version: 0.7.0 - last_generated_commit: effe5c4fa816021e724ca856d5640f2e55b14a8b + last_generated_commit: ef6a532bfd9ab7a944bdedd64c69a2b4042db58b apis: - path: google/cloud/geminidataanalytics/v1beta service_config: geminidataanalytics_v1beta.yaml @@ -2331,7 +2331,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-memorystore version: 0.2.0 - last_generated_commit: 3322511885371d2b2253f209ccc3aa60d4100cfd + last_generated_commit: ef6a532bfd9ab7a944bdedd64c69a2b4042db58b apis: - path: google/cloud/memorystore/v1beta service_config: memorystore_v1beta.yaml @@ -2862,7 +2862,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-recaptcha-enterprise version: 1.29.0 - last_generated_commit: 3322511885371d2b2253f209ccc3aa60d4100cfd + last_generated_commit: ef6a532bfd9ab7a944bdedd64c69a2b4042db58b apis: - path: google/cloud/recaptchaenterprise/v1 service_config: recaptchaenterprise_v1.yaml @@ -4262,7 +4262,7 @@ libraries: tag_format: '{id}-v{version}' - id: googleapis-common-protos version: 1.72.0 - last_generated_commit: effe5c4fa816021e724ca856d5640f2e55b14a8b + last_generated_commit: ef6a532bfd9ab7a944bdedd64c69a2b4042db58b apis: - path: google/api service_config: serviceconfig.yaml diff --git a/packages/google-ai-generativelanguage/google/ai/generativelanguage/__init__.py b/packages/google-ai-generativelanguage/google/ai/generativelanguage/__init__.py index fe4c2375268f..b0675c68b620 100644 --- a/packages/google-ai-generativelanguage/google/ai/generativelanguage/__init__.py +++ b/packages/google-ai-generativelanguage/google/ai/generativelanguage/__init__.py @@ -93,18 +93,21 @@ DynamicRetrievalConfig, ExecutableCode, FileData, + FileSearch, FunctionCall, FunctionCallingConfig, FunctionDeclaration, FunctionResponse, FunctionResponseBlob, FunctionResponsePart, + GoogleMaps, GoogleSearchRetrieval, GroundingPassage, GroundingPassages, Modality, ModalityTokenCount, Part, + RetrievalConfig, Schema, Tool, ToolConfig, @@ -325,17 +328,20 @@ "DynamicRetrievalConfig", "ExecutableCode", "FileData", + "FileSearch", "FunctionCall", "FunctionCallingConfig", "FunctionDeclaration", "FunctionResponse", "FunctionResponseBlob", "FunctionResponsePart", + "GoogleMaps", "GoogleSearchRetrieval", "GroundingPassage", "GroundingPassages", "ModalityTokenCount", "Part", + "RetrievalConfig", "Schema", "Tool", "ToolConfig", diff --git a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1/services/generative_service/async_client.py b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1/services/generative_service/async_client.py index bdd04db63b84..3e45acb1ff5f 100644 --- a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1/services/generative_service/async_client.py +++ b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1/services/generative_service/async_client.py @@ -349,7 +349,7 @@ async def sample_generate_content(): Args: request (Optional[Union[google.ai.generativelanguage_v1.types.GenerateContentRequest, dict]]): The request object. Request to generate a completion from - the model. NEXT ID: 18 + the model. model (:class:`str`): Required. The name of the ``Model`` to use for generating the completion. @@ -493,7 +493,7 @@ async def sample_stream_generate_content(): Args: request (Optional[Union[google.ai.generativelanguage_v1.types.GenerateContentRequest, dict]]): The request object. Request to generate a completion from - the model. NEXT ID: 18 + the model. model (:class:`str`): Required. The name of the ``Model`` to use for generating the completion. diff --git a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1/services/generative_service/client.py b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1/services/generative_service/client.py index 9d80ccec1d37..5bc3dcac7b2a 100644 --- a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1/services/generative_service/client.py +++ b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1/services/generative_service/client.py @@ -783,7 +783,7 @@ def sample_generate_content(): Args: request (Union[google.ai.generativelanguage_v1.types.GenerateContentRequest, dict]): The request object. Request to generate a completion from - the model. NEXT ID: 18 + the model. model (str): Required. The name of the ``Model`` to use for generating the completion. @@ -924,7 +924,7 @@ def sample_stream_generate_content(): Args: request (Union[google.ai.generativelanguage_v1.types.GenerateContentRequest, dict]): The request object. Request to generate a completion from - the model. NEXT ID: 18 + the model. model (str): Required. The name of the ``Model`` to use for generating the completion. diff --git a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1/services/generative_service/transports/rest.py b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1/services/generative_service/transports/rest.py index e289efb1ae59..b2c3671e4d67 100644 --- a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1/services/generative_service/transports/rest.py +++ b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1/services/generative_service/transports/rest.py @@ -1071,7 +1071,7 @@ def __call__( Args: request (~.generative_service.GenerateContentRequest): The request object. Request to generate a completion from - the model. NEXT ID: 18 + the model. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1244,7 +1244,7 @@ def __call__( Args: request (~.generative_service.GenerateContentRequest): The request object. Request to generate a completion from - the model. NEXT ID: 18 + the model. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1/types/generative_service.py b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1/types/generative_service.py index 684f0ef64b38..c46146a1f0de 100644 --- a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1/types/generative_service.py +++ b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1/types/generative_service.py @@ -97,8 +97,6 @@ class TaskType(proto.Enum): class GenerateContentRequest(proto.Message): r"""Request to generate a completion from the model. - NEXT ID: 18 - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -173,7 +171,6 @@ class GenerateContentRequest(proto.Message): class GenerationConfig(proto.Message): r"""Configuration options for model generation and outputs. Not all parameters are configurable for every model. - Next ID: 29 .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -672,6 +669,8 @@ class FinishReason(proto.Enum): NO_IMAGE (16): The model was expected to generate an image, but none was generated. + IMAGE_RECITATION (17): + Image generation stopped due to recitation. UNEXPECTED_TOOL_CALL (12): Model generated a tool call but no tools were enabled in the request. @@ -694,6 +693,7 @@ class FinishReason(proto.Enum): IMAGE_PROHIBITED_CONTENT = 14 IMAGE_OTHER = 15 NO_IMAGE = 16 + IMAGE_RECITATION = 17 UNEXPECTED_TOOL_CALL = 12 TOO_MANY_TOOL_CALLS = 13 @@ -940,6 +940,14 @@ class GroundingMetadata(proto.Message): web_search_queries (MutableSequence[str]): Web search queries for the following-up web search. + google_maps_widget_context_token (str): + Optional. Resource name of the Google Maps + widget context token that can be used with the + PlacesContextElement widget in order to render + contextual data. Only populated in the case that + grounding with Google Maps is enabled. + + This field is a member of `oneof`_ ``_google_maps_widget_context_token``. """ search_entry_point: "SearchEntryPoint" = proto.Field( @@ -968,6 +976,11 @@ class GroundingMetadata(proto.Message): proto.STRING, number=5, ) + google_maps_widget_context_token: str = proto.Field( + proto.STRING, + number=7, + optional=True, + ) class SearchEntryPoint(proto.Message): diff --git a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/__init__.py b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/__init__.py index 6f310100329e..832e33cf40c4 100644 --- a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/__init__.py +++ b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/__init__.py @@ -67,18 +67,21 @@ DynamicRetrievalConfig, ExecutableCode, FileData, + FileSearch, FunctionCall, FunctionCallingConfig, FunctionDeclaration, FunctionResponse, FunctionResponseBlob, FunctionResponsePart, + GoogleMaps, GoogleSearchRetrieval, GroundingPassage, GroundingPassages, Modality, ModalityTokenCount, Part, + RetrievalConfig, Schema, Tool, ToolConfig, @@ -444,6 +447,7 @@ def _get_version(dependency_name): "ExecutableCode", "File", "FileData", + "FileSearch", "FileServiceClient", "FunctionCall", "FunctionCallingConfig", @@ -470,6 +474,7 @@ def _get_version(dependency_name): "GetPermissionRequest", "GetTunedModelRequest", "GoAway", + "GoogleMaps", "GoogleSearchRetrieval", "GroundingAttribution", "GroundingChunk", @@ -523,6 +528,7 @@ def _get_version(dependency_name): "QueryDocumentResponse", "RealtimeInputConfig", "RelevantChunk", + "RetrievalConfig", "RetrievalMetadata", "RetrieverServiceClient", "SafetyFeedback", diff --git a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/generative_service/async_client.py b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/generative_service/async_client.py index f2234785408f..32e26bf6bbbf 100644 --- a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/generative_service/async_client.py +++ b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/generative_service/async_client.py @@ -354,7 +354,7 @@ async def sample_generate_content(): Args: request (Optional[Union[google.ai.generativelanguage_v1beta.types.GenerateContentRequest, dict]]): The request object. Request to generate a completion from - the model. NEXT ID: 18 + the model. model (:class:`str`): Required. The name of the ``Model`` to use for generating the completion. @@ -674,7 +674,7 @@ async def sample_stream_generate_content(): Args: request (Optional[Union[google.ai.generativelanguage_v1beta.types.GenerateContentRequest, dict]]): The request object. Request to generate a completion from - the model. NEXT ID: 18 + the model. model (:class:`str`): Required. The name of the ``Model`` to use for generating the completion. diff --git a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/generative_service/client.py b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/generative_service/client.py index ec5819194240..d63d617683b9 100644 --- a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/generative_service/client.py +++ b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/generative_service/client.py @@ -799,7 +799,7 @@ def sample_generate_content(): Args: request (Union[google.ai.generativelanguage_v1beta.types.GenerateContentRequest, dict]): The request object. Request to generate a completion from - the model. NEXT ID: 18 + the model. model (str): Required. The name of the ``Model`` to use for generating the completion. @@ -1113,7 +1113,7 @@ def sample_stream_generate_content(): Args: request (Union[google.ai.generativelanguage_v1beta.types.GenerateContentRequest, dict]): The request object. Request to generate a completion from - the model. NEXT ID: 18 + the model. model (str): Required. The name of the ``Model`` to use for generating the completion. diff --git a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/generative_service/transports/rest.py b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/generative_service/transports/rest.py index 3fe27b870696..ae4804cac76f 100644 --- a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/generative_service/transports/rest.py +++ b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/services/generative_service/transports/rest.py @@ -1306,7 +1306,7 @@ def __call__( Args: request (~.generative_service.GenerateContentRequest): The request object. Request to generate a completion from - the model. NEXT ID: 18 + the model. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1479,7 +1479,7 @@ def __call__( Args: request (~.generative_service.GenerateContentRequest): The request object. Request to generate a completion from - the model. NEXT ID: 18 + the model. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. diff --git a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/types/__init__.py b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/types/__init__.py index 2d63111dec1c..1e999f2f54b0 100644 --- a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/types/__init__.py +++ b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/types/__init__.py @@ -31,18 +31,21 @@ DynamicRetrievalConfig, ExecutableCode, FileData, + FileSearch, FunctionCall, FunctionCallingConfig, FunctionDeclaration, FunctionResponse, FunctionResponseBlob, FunctionResponsePart, + GoogleMaps, GoogleSearchRetrieval, GroundingPassage, GroundingPassages, Modality, ModalityTokenCount, Part, + RetrievalConfig, Schema, Tool, ToolConfig, @@ -245,17 +248,20 @@ "DynamicRetrievalConfig", "ExecutableCode", "FileData", + "FileSearch", "FunctionCall", "FunctionCallingConfig", "FunctionDeclaration", "FunctionResponse", "FunctionResponseBlob", "FunctionResponsePart", + "GoogleMaps", "GoogleSearchRetrieval", "GroundingPassage", "GroundingPassages", "ModalityTokenCount", "Part", + "RetrievalConfig", "Schema", "Tool", "ToolConfig", diff --git a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/types/content.py b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/types/content.py index 6d7f46657dd4..935c2eafde02 100644 --- a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/types/content.py +++ b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/types/content.py @@ -20,6 +20,7 @@ from google.protobuf import duration_pb2 # type: ignore from google.protobuf import struct_pb2 # type: ignore from google.type import interval_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore import proto # type: ignore __protobuf__ = proto.module( @@ -37,11 +38,14 @@ "ExecutableCode", "CodeExecutionResult", "Tool", + "GoogleMaps", "UrlContext", + "FileSearch", "GoogleSearchRetrieval", "DynamicRetrievalConfig", "CodeExecution", "ToolConfig", + "RetrievalConfig", "FunctionCallingConfig", "FunctionDeclaration", "FunctionCall", @@ -549,6 +553,14 @@ class Tool(proto.Message): url_context (google.ai.generativelanguage_v1beta.types.UrlContext): Optional. Tool to support URL context retrieval. + file_search (google.ai.generativelanguage_v1beta.types.FileSearch): + Optional. FileSearch tool type. + Tool to retrieve knowledge from Semantic + Retrieval corpora. + google_maps (google.ai.generativelanguage_v1beta.types.GoogleMaps): + Optional. Tool that allows grounding the + model's response with geospatial context related + to the user's query. """ class GoogleSearch(proto.Message): @@ -640,12 +652,110 @@ class Environment(proto.Enum): number=8, message="UrlContext", ) + file_search: "FileSearch" = proto.Field( + proto.MESSAGE, + number=9, + message="FileSearch", + ) + google_maps: "GoogleMaps" = proto.Field( + proto.MESSAGE, + number=11, + message="GoogleMaps", + ) + + +class GoogleMaps(proto.Message): + r"""The GoogleMaps Tool that provides geospatial context for the + user's query. + + Attributes: + enable_widget (bool): + Optional. Whether to return a widget context + token in the GroundingMetadata of the response. + Developers can use the widget context token to + render a Google Maps widget with geospatial + context related to the places that the model + references in the response. + """ + + enable_widget: bool = proto.Field( + proto.BOOL, + number=1, + ) class UrlContext(proto.Message): r"""Tool to support URL context retrieval.""" +class FileSearch(proto.Message): + r"""The FileSearch tool that retrieves knowledge from Semantic + Retrieval corpora. Files are imported to Semantic Retrieval + corpora using the ImportFile API. + + Attributes: + retrieval_resources (MutableSequence[google.ai.generativelanguage_v1beta.types.FileSearch.RetrievalResource]): + Required. Semantic retrieval resources to + retrieve from. Currently only supports one + corpus. In the future we may open up multiple + corpora support. + retrieval_config (google.ai.generativelanguage_v1beta.types.FileSearch.RetrievalConfig): + Optional. The configuration for the + retrieval. + """ + + class RetrievalResource(proto.Message): + r"""The semantic retrieval resource to retrieve from. + + Attributes: + rag_store_name (str): + Required. The name of the semantic retrieval resource to + retrieve from. Example: ``ragStores/my-rag-store-123`` + """ + + rag_store_name: str = proto.Field( + proto.STRING, + number=1, + ) + + class RetrievalConfig(proto.Message): + r"""Semantic retrieval configuration. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + top_k (int): + Optional. The number of semantic retrieval + chunks to retrieve. + + This field is a member of `oneof`_ ``_top_k``. + metadata_filter (str): + Optional. Metadata filter to apply to the + semantic retrieval documents and chunks. + """ + + top_k: int = proto.Field( + proto.INT32, + number=1, + optional=True, + ) + metadata_filter: str = proto.Field( + proto.STRING, + number=3, + ) + + retrieval_resources: MutableSequence[RetrievalResource] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=RetrievalResource, + ) + retrieval_config: RetrievalConfig = proto.Field( + proto.MESSAGE, + number=2, + message=RetrievalConfig, + ) + + class GoogleSearchRetrieval(proto.Message): r"""Tool to retrieve public web data for grounding, powered by Google. @@ -722,6 +832,8 @@ class ToolConfig(proto.Message): Attributes: function_calling_config (google.ai.generativelanguage_v1beta.types.FunctionCallingConfig): Optional. Function calling config. + retrieval_config (google.ai.generativelanguage_v1beta.types.RetrievalConfig): + Optional. Retrieval config. """ function_calling_config: "FunctionCallingConfig" = proto.Field( @@ -729,6 +841,34 @@ class ToolConfig(proto.Message): number=1, message="FunctionCallingConfig", ) + retrieval_config: "RetrievalConfig" = proto.Field( + proto.MESSAGE, + number=2, + message="RetrievalConfig", + ) + + +class RetrievalConfig(proto.Message): + r"""Retrieval config. + + Attributes: + lat_lng (google.type.latlng_pb2.LatLng): + Optional. The location of the user. + language_code (str): + Optional. The language code of the user. Language code for + content. Use language tags defined by + `BCP47 `__. + """ + + lat_lng: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=1, + message=latlng_pb2.LatLng, + ) + language_code: str = proto.Field( + proto.STRING, + number=2, + ) class FunctionCallingConfig(proto.Message): diff --git a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/types/generative_service.py b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/types/generative_service.py index f7dae3c61e8a..dd0599d93edd 100644 --- a/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/types/generative_service.py +++ b/packages/google-ai-generativelanguage/google/ai/generativelanguage_v1beta/types/generative_service.py @@ -128,8 +128,6 @@ class TaskType(proto.Enum): class GenerateContentRequest(proto.Message): r"""Request to generate a completion from the model. - NEXT ID: 18 - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -428,7 +426,6 @@ class ImageConfig(proto.Message): class GenerationConfig(proto.Message): r"""Configuration options for model generation and outputs. Not all parameters are configurable for every model. - Next ID: 29 .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -1552,6 +1549,14 @@ class GroundingMetadata(proto.Message): web_search_queries (MutableSequence[str]): Web search queries for the following-up web search. + google_maps_widget_context_token (str): + Optional. Resource name of the Google Maps + widget context token that can be used with the + PlacesContextElement widget in order to render + contextual data. Only populated in the case that + grounding with Google Maps is enabled. + + This field is a member of `oneof`_ ``_google_maps_widget_context_token``. """ search_entry_point: "SearchEntryPoint" = proto.Field( @@ -1580,6 +1585,11 @@ class GroundingMetadata(proto.Message): proto.STRING, number=5, ) + google_maps_widget_context_token: str = proto.Field( + proto.STRING, + number=7, + optional=True, + ) class SearchEntryPoint(proto.Message): @@ -1607,12 +1617,26 @@ class SearchEntryPoint(proto.Message): class GroundingChunk(proto.Message): r"""Grounding chunk. + 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: web (google.ai.generativelanguage_v1beta.types.GroundingChunk.Web): Grounding chunk from the web. + This field is a member of `oneof`_ ``chunk_type``. + retrieved_context (google.ai.generativelanguage_v1beta.types.GroundingChunk.RetrievedContext): + Optional. Grounding chunk from context + retrieved by the file search tool. + + This field is a member of `oneof`_ ``chunk_type``. + maps (google.ai.generativelanguage_v1beta.types.GroundingChunk.Maps): + Optional. Grounding chunk from Google Maps. + This field is a member of `oneof`_ ``chunk_type``. """ @@ -1643,12 +1667,183 @@ class Web(proto.Message): optional=True, ) + class RetrievedContext(proto.Message): + r"""Chunk from context retrieved by the file search tool. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + uri (str): + Optional. URI reference of the semantic + retrieval document. + + This field is a member of `oneof`_ ``_uri``. + title (str): + Optional. Title of the document. + + This field is a member of `oneof`_ ``_title``. + text (str): + Optional. Text of the chunk. + + This field is a member of `oneof`_ ``_text``. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + title: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + text: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + + class Maps(proto.Message): + r"""A grounding chunk from Google Maps. A Maps chunk corresponds + to a single place. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + uri (str): + URI reference of the place. + + This field is a member of `oneof`_ ``_uri``. + title (str): + Title of the place. + + This field is a member of `oneof`_ ``_title``. + text (str): + Text description of the place answer. + + This field is a member of `oneof`_ ``_text``. + place_id (str): + This ID of the place, in ``places/{place_id}`` format. A + user can use this ID to look up that place. + + This field is a member of `oneof`_ ``_place_id``. + place_answer_sources (google.ai.generativelanguage_v1beta.types.GroundingChunk.Maps.PlaceAnswerSources): + Sources that provide answers about the + features of a given place in Google Maps. + + This field is a member of `oneof`_ ``_place_answer_sources``. + """ + + class PlaceAnswerSources(proto.Message): + r"""Collection of sources that provide answers about the features + of a given place in Google Maps. Each PlaceAnswerSources message + corresponds to a specific place in Google Maps. The Google Maps + tool used these sources in order to answer questions about + features of the place (e.g: "does Bar Foo have Wifi" or "is Foo + Bar wheelchair accessible?"). Currently we only support review + snippets as sources. + + Attributes: + review_snippets (MutableSequence[google.ai.generativelanguage_v1beta.types.GroundingChunk.Maps.PlaceAnswerSources.ReviewSnippet]): + Snippets of reviews that are used to generate + answers about the features of a given place in + Google Maps. + """ + + class ReviewSnippet(proto.Message): + r"""Encapsulates a snippet of a user review that answers a + question about the features of a specific place in Google Maps. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + review_id (str): + The ID of the review snippet. + + This field is a member of `oneof`_ ``_review_id``. + google_maps_uri (str): + A link that corresponds to the user review on + Google Maps. + + This field is a member of `oneof`_ ``_google_maps_uri``. + title (str): + Title of the review. + + This field is a member of `oneof`_ ``_title``. + """ + + review_id: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + google_maps_uri: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + title: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + + review_snippets: MutableSequence[ + "GroundingChunk.Maps.PlaceAnswerSources.ReviewSnippet" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="GroundingChunk.Maps.PlaceAnswerSources.ReviewSnippet", + ) + + uri: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + title: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + text: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + place_id: str = proto.Field( + proto.STRING, + number=4, + optional=True, + ) + place_answer_sources: "GroundingChunk.Maps.PlaceAnswerSources" = proto.Field( + proto.MESSAGE, + number=5, + optional=True, + message="GroundingChunk.Maps.PlaceAnswerSources", + ) + web: Web = proto.Field( proto.MESSAGE, number=1, oneof="chunk_type", message=Web, ) + retrieved_context: RetrievedContext = proto.Field( + proto.MESSAGE, + number=2, + oneof="chunk_type", + message=RetrievedContext, + ) + maps: Maps = proto.Field( + proto.MESSAGE, + number=3, + oneof="chunk_type", + message=Maps, + ) class Segment(proto.Message): diff --git a/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_cache_service.py b/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_cache_service.py index b7f57d02a757..9b9cc7d0fdae 100644 --- a/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_cache_service.py +++ b/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_cache_service.py @@ -57,6 +57,7 @@ from google.protobuf import struct_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore from google.type import interval_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore from google.ai.generativelanguage_v1beta.services.cache_service import ( CacheServiceAsyncClient, @@ -4528,6 +4529,14 @@ def test_create_cached_content_rest_call_success(request_type): ], }, "url_context": {}, + "file_search": { + "retrieval_resources": [{"rag_store_name": "rag_store_name_value"}], + "retrieval_config": { + "top_k": 541, + "metadata_filter": "metadata_filter_value", + }, + }, + "google_maps": {"enable_widget": True}, } ], "tool_config": { @@ -4537,7 +4546,11 @@ def test_create_cached_content_rest_call_success(request_type): "allowed_function_names_value1", "allowed_function_names_value2", ], - } + }, + "retrieval_config": { + "lat_lng": {"latitude": 0.86, "longitude": 0.971}, + "language_code": "language_code_value", + }, }, "create_time": {}, "update_time": {}, @@ -4991,6 +5004,14 @@ def test_update_cached_content_rest_call_success(request_type): ], }, "url_context": {}, + "file_search": { + "retrieval_resources": [{"rag_store_name": "rag_store_name_value"}], + "retrieval_config": { + "top_k": 541, + "metadata_filter": "metadata_filter_value", + }, + }, + "google_maps": {"enable_widget": True}, } ], "tool_config": { @@ -5000,7 +5021,11 @@ def test_update_cached_content_rest_call_success(request_type): "allowed_function_names_value1", "allowed_function_names_value2", ], - } + }, + "retrieval_config": { + "lat_lng": {"latitude": 0.86, "longitude": 0.971}, + "language_code": "language_code_value", + }, }, "create_time": {}, "update_time": {}, diff --git a/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_generative_service.py b/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_generative_service.py index b19a1994f4b0..4f7850c9d30f 100644 --- a/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_generative_service.py +++ b/packages/google-ai-generativelanguage/tests/unit/gapic/generativelanguage_v1beta/test_generative_service.py @@ -56,6 +56,7 @@ from google.protobuf import struct_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore from google.type import interval_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore from google.ai.generativelanguage_v1beta.services.generative_service import ( GenerativeServiceAsyncClient, diff --git a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/async_client.py b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/async_client.py index 2f0c7e491572..bafd1540159c 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/async_client.py +++ b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/async_client.py @@ -553,21 +553,38 @@ async def list_messages( metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListMessagesAsyncPager: r"""Lists messages in a space that the caller is a member of, - including messages from blocked members and spaces. If you list - messages from a space with no messages, the response is an empty - object. When using a REST/HTTP interface, the response contains - an empty JSON object, ``{}``. For an example, see `List + including messages from blocked members and spaces. System + messages, like those announcing new space members, aren't + included. If you list messages from a space with no messages, + the response is an empty object. When using a REST/HTTP + interface, the response contains an empty JSON object, ``{}``. + For an example, see `List messages `__. - Requires `user - authentication `__ - with one of the following `authorization - scopes `__: + Supports the following types of + `authentication `__: - - ``https://www.googleapis.com/auth/chat.messages.readonly`` - - ``https://www.googleapis.com/auth/chat.messages`` - - ``https://www.googleapis.com/auth/chat.import`` (import mode - spaces only) + - `App + authentication `__ + with `administrator + approval `__ in + `Developer + Preview `__ + with the authorization scope: + + - ``https://www.googleapis.com/auth/chat.app.messages.readonly``. + When using this authentication scope, this method only + returns public messages in a space. It doesn't include + private messages. + + - `User + authentication `__ + with one of the following authorization scopes: + + - ``https://www.googleapis.com/auth/chat.messages.readonly`` + - ``https://www.googleapis.com/auth/chat.messages`` + - ``https://www.googleapis.com/auth/chat.import`` (import mode + spaces only) .. code-block:: python @@ -1024,9 +1041,21 @@ async def get_message( - `App authentication `__ - with the authorization scope: + with one of the following authorization scopes: - - ``https://www.googleapis.com/auth/chat.bot`` + - ``https://www.googleapis.com/auth/chat.bot``: When using + this authorization scope, this method returns details about + a message the Chat app has access to, like direct messages + and `slash + commands `__ + that invoke the Chat app. + - ``https://www.googleapis.com/auth/chat.app.messages.readonly`` + with `administrator + approval `__ + (available in `Developer + Preview `__). + When using this authentication scope, this method returns + details about a public message in a space. - `User authentication `__ @@ -1774,7 +1803,10 @@ async def search_spaces( metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.SearchSpacesAsyncPager: r"""Returns a list of spaces in a Google Workspace organization - based on an administrator's search. + based on an administrator's search. In the request, set + ``use_admin_access`` to ``true``. For an example, see `Search + for and manage + spaces `__. Requires `user authentication with administrator privileges `__ @@ -1784,8 +1816,6 @@ async def search_spaces( - ``https://www.googleapis.com/auth/chat.admin.spaces.readonly`` - ``https://www.googleapis.com/auth/chat.admin.spaces`` - In the request, set ``use_admin_access`` to ``true``. - .. code-block:: python # This snippet has been automatically generated and should be regarded as a @@ -2436,8 +2466,12 @@ async def sample_update_space(): You can update the following fields for a space: - ``space_details``: Updates the space's description. - Supports up to 150 characters. + ``space_details``: Updates the space's description and + guidelines. You must pass both description and + guidelines in the update request as + [``SpaceDetails``][google.chat.v1.Space.SpaceDetails]. + If you only want to update one of the fields, pass the + existing value for the other field. ``display_name``: Only supports updating the display name for spaces where ``spaceType`` field is ``SPACE``. @@ -2490,9 +2524,8 @@ async def sample_update_space(): settings `__ of a space. When updating permission settings, you can only specify ``permissionSettings`` field masks; you - cannot update other field masks at the same time. - ``permissionSettings`` is not supported with - ``useAdminAccess``. The supported field masks include: + cannot update other field masks at the same time. The + supported field masks include: - ``permission_settings.manageMembersAndGroups`` - ``permission_settings.modifySpaceDetails`` @@ -4785,23 +4818,39 @@ async def get_space_event( Note: The ``permissionSettings`` field is not returned in the Space object of the Space event data for this request. - Requires `user - authentication `__ + Supports the following types of + `authentication `__ with an `authorization scope `__ appropriate for reading the requested data: - - ``https://www.googleapis.com/auth/chat.spaces.readonly`` - - ``https://www.googleapis.com/auth/chat.spaces`` - - ``https://www.googleapis.com/auth/chat.messages.readonly`` - - ``https://www.googleapis.com/auth/chat.messages`` - - ``https://www.googleapis.com/auth/chat.messages.reactions.readonly`` - - ``https://www.googleapis.com/auth/chat.messages.reactions`` - - ``https://www.googleapis.com/auth/chat.memberships.readonly`` - - ``https://www.googleapis.com/auth/chat.memberships`` + - `App + authentication `__ + with `administrator + approval `__ in + `Developer + Preview `__ + with one of the following authorization scopes: - To get an event, the authenticated user must be a member of the - space. + - ``https://www.googleapis.com/auth/chat.app.spaces`` + - ``https://www.googleapis.com/auth/chat.app.messages.readonly`` + - ``https://www.googleapis.com/auth/chat.app.memberships`` + + - `User + authentication `__ + with one of the following authorization scopes: + + - ``https://www.googleapis.com/auth/chat.spaces.readonly`` + - ``https://www.googleapis.com/auth/chat.spaces`` + - ``https://www.googleapis.com/auth/chat.messages.readonly`` + - ``https://www.googleapis.com/auth/chat.messages`` + - ``https://www.googleapis.com/auth/chat.messages.reactions.readonly`` + - ``https://www.googleapis.com/auth/chat.messages.reactions`` + - ``https://www.googleapis.com/auth/chat.memberships.readonly`` + - ``https://www.googleapis.com/auth/chat.memberships`` + + To get an event, the authenticated caller must be a member of + the space. For an example, see `Get details about an event from a Google Chat @@ -4928,22 +4977,38 @@ async def list_space_events( requested period, the event payload contains an empty ``Membership`` resource. - Requires `user - authentication `__ + Supports the following types of + `authentication `__ with an `authorization scope `__ appropriate for reading the requested data: - - ``https://www.googleapis.com/auth/chat.spaces.readonly`` - - ``https://www.googleapis.com/auth/chat.spaces`` - - ``https://www.googleapis.com/auth/chat.messages.readonly`` - - ``https://www.googleapis.com/auth/chat.messages`` - - ``https://www.googleapis.com/auth/chat.messages.reactions.readonly`` - - ``https://www.googleapis.com/auth/chat.messages.reactions`` - - ``https://www.googleapis.com/auth/chat.memberships.readonly`` - - ``https://www.googleapis.com/auth/chat.memberships`` + - `App + authentication `__ + with `administrator + approval `__ in + `Developer + Preview `__ + with one of the following authorization scopes: + + - ``https://www.googleapis.com/auth/chat.app.spaces`` + - ``https://www.googleapis.com/auth/chat.app.messages.readonly`` + - ``https://www.googleapis.com/auth/chat.app.memberships`` + + - `User + authentication `__ + with one of the following authorization scopes: + + - ``https://www.googleapis.com/auth/chat.spaces.readonly`` + - ``https://www.googleapis.com/auth/chat.spaces`` + - ``https://www.googleapis.com/auth/chat.messages.readonly`` + - ``https://www.googleapis.com/auth/chat.messages`` + - ``https://www.googleapis.com/auth/chat.messages.reactions.readonly`` + - ``https://www.googleapis.com/auth/chat.messages.reactions`` + - ``https://www.googleapis.com/auth/chat.memberships.readonly`` + - ``https://www.googleapis.com/auth/chat.memberships`` - To list events, the authenticated user must be a member of the + To list events, the authenticated caller must be a member of the space. For an example, see `List events from a Google Chat diff --git a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/client.py b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/client.py index 01a6d59c742d..3294c399ad55 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/client.py +++ b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/client.py @@ -1159,21 +1159,38 @@ def list_messages( metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListMessagesPager: r"""Lists messages in a space that the caller is a member of, - including messages from blocked members and spaces. If you list - messages from a space with no messages, the response is an empty - object. When using a REST/HTTP interface, the response contains - an empty JSON object, ``{}``. For an example, see `List + including messages from blocked members and spaces. System + messages, like those announcing new space members, aren't + included. If you list messages from a space with no messages, + the response is an empty object. When using a REST/HTTP + interface, the response contains an empty JSON object, ``{}``. + For an example, see `List messages `__. - Requires `user - authentication `__ - with one of the following `authorization - scopes `__: + Supports the following types of + `authentication `__: - - ``https://www.googleapis.com/auth/chat.messages.readonly`` - - ``https://www.googleapis.com/auth/chat.messages`` - - ``https://www.googleapis.com/auth/chat.import`` (import mode - spaces only) + - `App + authentication `__ + with `administrator + approval `__ in + `Developer + Preview `__ + with the authorization scope: + + - ``https://www.googleapis.com/auth/chat.app.messages.readonly``. + When using this authentication scope, this method only + returns public messages in a space. It doesn't include + private messages. + + - `User + authentication `__ + with one of the following authorization scopes: + + - ``https://www.googleapis.com/auth/chat.messages.readonly`` + - ``https://www.googleapis.com/auth/chat.messages`` + - ``https://www.googleapis.com/auth/chat.import`` (import mode + spaces only) .. code-block:: python @@ -1621,9 +1638,21 @@ def get_message( - `App authentication `__ - with the authorization scope: + with one of the following authorization scopes: - - ``https://www.googleapis.com/auth/chat.bot`` + - ``https://www.googleapis.com/auth/chat.bot``: When using + this authorization scope, this method returns details about + a message the Chat app has access to, like direct messages + and `slash + commands `__ + that invoke the Chat app. + - ``https://www.googleapis.com/auth/chat.app.messages.readonly`` + with `administrator + approval `__ + (available in `Developer + Preview `__). + When using this authentication scope, this method returns + details about a public message in a space. - `User authentication `__ @@ -2355,7 +2384,10 @@ def search_spaces( metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.SearchSpacesPager: r"""Returns a list of spaces in a Google Workspace organization - based on an administrator's search. + based on an administrator's search. In the request, set + ``use_admin_access`` to ``true``. For an example, see `Search + for and manage + spaces `__. Requires `user authentication with administrator privileges `__ @@ -2365,8 +2397,6 @@ def search_spaces( - ``https://www.googleapis.com/auth/chat.admin.spaces.readonly`` - ``https://www.googleapis.com/auth/chat.admin.spaces`` - In the request, set ``use_admin_access`` to ``true``. - .. code-block:: python # This snippet has been automatically generated and should be regarded as a @@ -3007,8 +3037,12 @@ def sample_update_space(): You can update the following fields for a space: - ``space_details``: Updates the space's description. - Supports up to 150 characters. + ``space_details``: Updates the space's description and + guidelines. You must pass both description and + guidelines in the update request as + [``SpaceDetails``][google.chat.v1.Space.SpaceDetails]. + If you only want to update one of the fields, pass the + existing value for the other field. ``display_name``: Only supports updating the display name for spaces where ``spaceType`` field is ``SPACE``. @@ -3061,9 +3095,8 @@ def sample_update_space(): settings `__ of a space. When updating permission settings, you can only specify ``permissionSettings`` field masks; you - cannot update other field masks at the same time. - ``permissionSettings`` is not supported with - ``useAdminAccess``. The supported field masks include: + cannot update other field masks at the same time. The + supported field masks include: - ``permission_settings.manageMembersAndGroups`` - ``permission_settings.modifySpaceDetails`` @@ -5308,23 +5341,39 @@ def get_space_event( Note: The ``permissionSettings`` field is not returned in the Space object of the Space event data for this request. - Requires `user - authentication `__ + Supports the following types of + `authentication `__ with an `authorization scope `__ appropriate for reading the requested data: - - ``https://www.googleapis.com/auth/chat.spaces.readonly`` - - ``https://www.googleapis.com/auth/chat.spaces`` - - ``https://www.googleapis.com/auth/chat.messages.readonly`` - - ``https://www.googleapis.com/auth/chat.messages`` - - ``https://www.googleapis.com/auth/chat.messages.reactions.readonly`` - - ``https://www.googleapis.com/auth/chat.messages.reactions`` - - ``https://www.googleapis.com/auth/chat.memberships.readonly`` - - ``https://www.googleapis.com/auth/chat.memberships`` + - `App + authentication `__ + with `administrator + approval `__ in + `Developer + Preview `__ + with one of the following authorization scopes: - To get an event, the authenticated user must be a member of the - space. + - ``https://www.googleapis.com/auth/chat.app.spaces`` + - ``https://www.googleapis.com/auth/chat.app.messages.readonly`` + - ``https://www.googleapis.com/auth/chat.app.memberships`` + + - `User + authentication `__ + with one of the following authorization scopes: + + - ``https://www.googleapis.com/auth/chat.spaces.readonly`` + - ``https://www.googleapis.com/auth/chat.spaces`` + - ``https://www.googleapis.com/auth/chat.messages.readonly`` + - ``https://www.googleapis.com/auth/chat.messages`` + - ``https://www.googleapis.com/auth/chat.messages.reactions.readonly`` + - ``https://www.googleapis.com/auth/chat.messages.reactions`` + - ``https://www.googleapis.com/auth/chat.memberships.readonly`` + - ``https://www.googleapis.com/auth/chat.memberships`` + + To get an event, the authenticated caller must be a member of + the space. For an example, see `Get details about an event from a Google Chat @@ -5448,22 +5497,38 @@ def list_space_events( requested period, the event payload contains an empty ``Membership`` resource. - Requires `user - authentication `__ + Supports the following types of + `authentication `__ with an `authorization scope `__ appropriate for reading the requested data: - - ``https://www.googleapis.com/auth/chat.spaces.readonly`` - - ``https://www.googleapis.com/auth/chat.spaces`` - - ``https://www.googleapis.com/auth/chat.messages.readonly`` - - ``https://www.googleapis.com/auth/chat.messages`` - - ``https://www.googleapis.com/auth/chat.messages.reactions.readonly`` - - ``https://www.googleapis.com/auth/chat.messages.reactions`` - - ``https://www.googleapis.com/auth/chat.memberships.readonly`` - - ``https://www.googleapis.com/auth/chat.memberships`` + - `App + authentication `__ + with `administrator + approval `__ in + `Developer + Preview `__ + with one of the following authorization scopes: + + - ``https://www.googleapis.com/auth/chat.app.spaces`` + - ``https://www.googleapis.com/auth/chat.app.messages.readonly`` + - ``https://www.googleapis.com/auth/chat.app.memberships`` + + - `User + authentication `__ + with one of the following authorization scopes: + + - ``https://www.googleapis.com/auth/chat.spaces.readonly`` + - ``https://www.googleapis.com/auth/chat.spaces`` + - ``https://www.googleapis.com/auth/chat.messages.readonly`` + - ``https://www.googleapis.com/auth/chat.messages`` + - ``https://www.googleapis.com/auth/chat.messages.reactions.readonly`` + - ``https://www.googleapis.com/auth/chat.messages.reactions`` + - ``https://www.googleapis.com/auth/chat.memberships.readonly`` + - ``https://www.googleapis.com/auth/chat.memberships`` - To list events, the authenticated user must be a member of the + To list events, the authenticated caller must be a member of the space. For an example, see `List events from a Google Chat diff --git a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/base.py b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/base.py index b149d389b723..12b13894f2f2 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/base.py +++ b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/base.py @@ -64,6 +64,7 @@ class ChatServiceTransport(abc.ABC): "https://www.googleapis.com/auth/chat.admin.spaces.readonly", "https://www.googleapis.com/auth/chat.app.delete", "https://www.googleapis.com/auth/chat.app.memberships", + "https://www.googleapis.com/auth/chat.app.messages.readonly", "https://www.googleapis.com/auth/chat.app.spaces", "https://www.googleapis.com/auth/chat.app.spaces.create", "https://www.googleapis.com/auth/chat.bot", diff --git a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/grpc.py b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/grpc.py index 90e67241bba6..616ba4406cd0 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/grpc.py +++ b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/grpc.py @@ -423,21 +423,38 @@ def list_messages( r"""Return a callable for the list messages method over gRPC. Lists messages in a space that the caller is a member of, - including messages from blocked members and spaces. If you list - messages from a space with no messages, the response is an empty - object. When using a REST/HTTP interface, the response contains - an empty JSON object, ``{}``. For an example, see `List + including messages from blocked members and spaces. System + messages, like those announcing new space members, aren't + included. If you list messages from a space with no messages, + the response is an empty object. When using a REST/HTTP + interface, the response contains an empty JSON object, ``{}``. + For an example, see `List messages `__. - Requires `user - authentication `__ - with one of the following `authorization - scopes `__: + Supports the following types of + `authentication `__: - - ``https://www.googleapis.com/auth/chat.messages.readonly`` - - ``https://www.googleapis.com/auth/chat.messages`` - - ``https://www.googleapis.com/auth/chat.import`` (import mode - spaces only) + - `App + authentication `__ + with `administrator + approval `__ in + `Developer + Preview `__ + with the authorization scope: + + - ``https://www.googleapis.com/auth/chat.app.messages.readonly``. + When using this authentication scope, this method only + returns public messages in a space. It doesn't include + private messages. + + - `User + authentication `__ + with one of the following authorization scopes: + + - ``https://www.googleapis.com/auth/chat.messages.readonly`` + - ``https://www.googleapis.com/auth/chat.messages`` + - ``https://www.googleapis.com/auth/chat.import`` (import mode + spaces only) Returns: Callable[[~.ListMessagesRequest], @@ -590,9 +607,21 @@ def get_message(self) -> Callable[[message.GetMessageRequest], message.Message]: - `App authentication `__ - with the authorization scope: + with one of the following authorization scopes: - - ``https://www.googleapis.com/auth/chat.bot`` + - ``https://www.googleapis.com/auth/chat.bot``: When using + this authorization scope, this method returns details about + a message the Chat app has access to, like direct messages + and `slash + commands `__ + that invoke the Chat app. + - ``https://www.googleapis.com/auth/chat.app.messages.readonly`` + with `administrator + approval `__ + (available in `Developer + Preview `__). + When using this authentication scope, this method returns + details about a public message in a space. - `User authentication `__ @@ -857,7 +886,10 @@ def search_spaces( r"""Return a callable for the search spaces method over gRPC. Returns a list of spaces in a Google Workspace organization - based on an administrator's search. + based on an administrator's search. In the request, set + ``use_admin_access`` to ``true``. For an example, see `Search + for and manage + spaces `__. Requires `user authentication with administrator privileges `__ @@ -867,8 +899,6 @@ def search_spaces( - ``https://www.googleapis.com/auth/chat.admin.spaces.readonly`` - ``https://www.googleapis.com/auth/chat.admin.spaces`` - In the request, set ``use_admin_access`` to ``true``. - Returns: Callable[[~.SearchSpacesRequest], ~.SearchSpacesResponse]: @@ -1928,23 +1958,39 @@ def get_space_event( Note: The ``permissionSettings`` field is not returned in the Space object of the Space event data for this request. - Requires `user - authentication `__ + Supports the following types of + `authentication `__ with an `authorization scope `__ appropriate for reading the requested data: - - ``https://www.googleapis.com/auth/chat.spaces.readonly`` - - ``https://www.googleapis.com/auth/chat.spaces`` - - ``https://www.googleapis.com/auth/chat.messages.readonly`` - - ``https://www.googleapis.com/auth/chat.messages`` - - ``https://www.googleapis.com/auth/chat.messages.reactions.readonly`` - - ``https://www.googleapis.com/auth/chat.messages.reactions`` - - ``https://www.googleapis.com/auth/chat.memberships.readonly`` - - ``https://www.googleapis.com/auth/chat.memberships`` + - `App + authentication `__ + with `administrator + approval `__ in + `Developer + Preview `__ + with one of the following authorization scopes: - To get an event, the authenticated user must be a member of the - space. + - ``https://www.googleapis.com/auth/chat.app.spaces`` + - ``https://www.googleapis.com/auth/chat.app.messages.readonly`` + - ``https://www.googleapis.com/auth/chat.app.memberships`` + + - `User + authentication `__ + with one of the following authorization scopes: + + - ``https://www.googleapis.com/auth/chat.spaces.readonly`` + - ``https://www.googleapis.com/auth/chat.spaces`` + - ``https://www.googleapis.com/auth/chat.messages.readonly`` + - ``https://www.googleapis.com/auth/chat.messages`` + - ``https://www.googleapis.com/auth/chat.messages.reactions.readonly`` + - ``https://www.googleapis.com/auth/chat.messages.reactions`` + - ``https://www.googleapis.com/auth/chat.memberships.readonly`` + - ``https://www.googleapis.com/auth/chat.memberships`` + + To get an event, the authenticated caller must be a member of + the space. For an example, see `Get details about an event from a Google Chat @@ -1985,22 +2031,38 @@ def list_space_events( requested period, the event payload contains an empty ``Membership`` resource. - Requires `user - authentication `__ + Supports the following types of + `authentication `__ with an `authorization scope `__ appropriate for reading the requested data: - - ``https://www.googleapis.com/auth/chat.spaces.readonly`` - - ``https://www.googleapis.com/auth/chat.spaces`` - - ``https://www.googleapis.com/auth/chat.messages.readonly`` - - ``https://www.googleapis.com/auth/chat.messages`` - - ``https://www.googleapis.com/auth/chat.messages.reactions.readonly`` - - ``https://www.googleapis.com/auth/chat.messages.reactions`` - - ``https://www.googleapis.com/auth/chat.memberships.readonly`` - - ``https://www.googleapis.com/auth/chat.memberships`` + - `App + authentication `__ + with `administrator + approval `__ in + `Developer + Preview `__ + with one of the following authorization scopes: + + - ``https://www.googleapis.com/auth/chat.app.spaces`` + - ``https://www.googleapis.com/auth/chat.app.messages.readonly`` + - ``https://www.googleapis.com/auth/chat.app.memberships`` + + - `User + authentication `__ + with one of the following authorization scopes: + + - ``https://www.googleapis.com/auth/chat.spaces.readonly`` + - ``https://www.googleapis.com/auth/chat.spaces`` + - ``https://www.googleapis.com/auth/chat.messages.readonly`` + - ``https://www.googleapis.com/auth/chat.messages`` + - ``https://www.googleapis.com/auth/chat.messages.reactions.readonly`` + - ``https://www.googleapis.com/auth/chat.messages.reactions`` + - ``https://www.googleapis.com/auth/chat.memberships.readonly`` + - ``https://www.googleapis.com/auth/chat.memberships`` - To list events, the authenticated user must be a member of the + To list events, the authenticated caller must be a member of the space. For an example, see `List events from a Google Chat diff --git a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/grpc_asyncio.py b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/grpc_asyncio.py index cb24adc72b78..8141a8d66656 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/grpc_asyncio.py +++ b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/transports/grpc_asyncio.py @@ -433,21 +433,38 @@ def list_messages( r"""Return a callable for the list messages method over gRPC. Lists messages in a space that the caller is a member of, - including messages from blocked members and spaces. If you list - messages from a space with no messages, the response is an empty - object. When using a REST/HTTP interface, the response contains - an empty JSON object, ``{}``. For an example, see `List + including messages from blocked members and spaces. System + messages, like those announcing new space members, aren't + included. If you list messages from a space with no messages, + the response is an empty object. When using a REST/HTTP + interface, the response contains an empty JSON object, ``{}``. + For an example, see `List messages `__. - Requires `user - authentication `__ - with one of the following `authorization - scopes `__: + Supports the following types of + `authentication `__: - - ``https://www.googleapis.com/auth/chat.messages.readonly`` - - ``https://www.googleapis.com/auth/chat.messages`` - - ``https://www.googleapis.com/auth/chat.import`` (import mode - spaces only) + - `App + authentication `__ + with `administrator + approval `__ in + `Developer + Preview `__ + with the authorization scope: + + - ``https://www.googleapis.com/auth/chat.app.messages.readonly``. + When using this authentication scope, this method only + returns public messages in a space. It doesn't include + private messages. + + - `User + authentication `__ + with one of the following authorization scopes: + + - ``https://www.googleapis.com/auth/chat.messages.readonly`` + - ``https://www.googleapis.com/auth/chat.messages`` + - ``https://www.googleapis.com/auth/chat.import`` (import mode + spaces only) Returns: Callable[[~.ListMessagesRequest], @@ -603,9 +620,21 @@ def get_message( - `App authentication `__ - with the authorization scope: + with one of the following authorization scopes: - - ``https://www.googleapis.com/auth/chat.bot`` + - ``https://www.googleapis.com/auth/chat.bot``: When using + this authorization scope, this method returns details about + a message the Chat app has access to, like direct messages + and `slash + commands `__ + that invoke the Chat app. + - ``https://www.googleapis.com/auth/chat.app.messages.readonly`` + with `administrator + approval `__ + (available in `Developer + Preview `__). + When using this authentication scope, this method returns + details about a public message in a space. - `User authentication `__ @@ -871,7 +900,10 @@ def search_spaces( r"""Return a callable for the search spaces method over gRPC. Returns a list of spaces in a Google Workspace organization - based on an administrator's search. + based on an administrator's search. In the request, set + ``use_admin_access`` to ``true``. For an example, see `Search + for and manage + spaces `__. Requires `user authentication with administrator privileges `__ @@ -881,8 +913,6 @@ def search_spaces( - ``https://www.googleapis.com/auth/chat.admin.spaces.readonly`` - ``https://www.googleapis.com/auth/chat.admin.spaces`` - In the request, set ``use_admin_access`` to ``true``. - Returns: Callable[[~.SearchSpacesRequest], Awaitable[~.SearchSpacesResponse]]: @@ -1962,23 +1992,39 @@ def get_space_event( Note: The ``permissionSettings`` field is not returned in the Space object of the Space event data for this request. - Requires `user - authentication `__ + Supports the following types of + `authentication `__ with an `authorization scope `__ appropriate for reading the requested data: - - ``https://www.googleapis.com/auth/chat.spaces.readonly`` - - ``https://www.googleapis.com/auth/chat.spaces`` - - ``https://www.googleapis.com/auth/chat.messages.readonly`` - - ``https://www.googleapis.com/auth/chat.messages`` - - ``https://www.googleapis.com/auth/chat.messages.reactions.readonly`` - - ``https://www.googleapis.com/auth/chat.messages.reactions`` - - ``https://www.googleapis.com/auth/chat.memberships.readonly`` - - ``https://www.googleapis.com/auth/chat.memberships`` + - `App + authentication `__ + with `administrator + approval `__ in + `Developer + Preview `__ + with one of the following authorization scopes: - To get an event, the authenticated user must be a member of the - space. + - ``https://www.googleapis.com/auth/chat.app.spaces`` + - ``https://www.googleapis.com/auth/chat.app.messages.readonly`` + - ``https://www.googleapis.com/auth/chat.app.memberships`` + + - `User + authentication `__ + with one of the following authorization scopes: + + - ``https://www.googleapis.com/auth/chat.spaces.readonly`` + - ``https://www.googleapis.com/auth/chat.spaces`` + - ``https://www.googleapis.com/auth/chat.messages.readonly`` + - ``https://www.googleapis.com/auth/chat.messages`` + - ``https://www.googleapis.com/auth/chat.messages.reactions.readonly`` + - ``https://www.googleapis.com/auth/chat.messages.reactions`` + - ``https://www.googleapis.com/auth/chat.memberships.readonly`` + - ``https://www.googleapis.com/auth/chat.memberships`` + + To get an event, the authenticated caller must be a member of + the space. For an example, see `Get details about an event from a Google Chat @@ -2020,22 +2066,38 @@ def list_space_events( requested period, the event payload contains an empty ``Membership`` resource. - Requires `user - authentication `__ + Supports the following types of + `authentication `__ with an `authorization scope `__ appropriate for reading the requested data: - - ``https://www.googleapis.com/auth/chat.spaces.readonly`` - - ``https://www.googleapis.com/auth/chat.spaces`` - - ``https://www.googleapis.com/auth/chat.messages.readonly`` - - ``https://www.googleapis.com/auth/chat.messages`` - - ``https://www.googleapis.com/auth/chat.messages.reactions.readonly`` - - ``https://www.googleapis.com/auth/chat.messages.reactions`` - - ``https://www.googleapis.com/auth/chat.memberships.readonly`` - - ``https://www.googleapis.com/auth/chat.memberships`` + - `App + authentication `__ + with `administrator + approval `__ in + `Developer + Preview `__ + with one of the following authorization scopes: + + - ``https://www.googleapis.com/auth/chat.app.spaces`` + - ``https://www.googleapis.com/auth/chat.app.messages.readonly`` + - ``https://www.googleapis.com/auth/chat.app.memberships`` + + - `User + authentication `__ + with one of the following authorization scopes: + + - ``https://www.googleapis.com/auth/chat.spaces.readonly`` + - ``https://www.googleapis.com/auth/chat.spaces`` + - ``https://www.googleapis.com/auth/chat.messages.readonly`` + - ``https://www.googleapis.com/auth/chat.messages`` + - ``https://www.googleapis.com/auth/chat.messages.reactions.readonly`` + - ``https://www.googleapis.com/auth/chat.messages.reactions`` + - ``https://www.googleapis.com/auth/chat.memberships.readonly`` + - ``https://www.googleapis.com/auth/chat.memberships`` - To list events, the authenticated user must be a member of the + To list events, the authenticated caller must be a member of the space. For an example, see `List events from a Google Chat diff --git a/packages/google-apps-chat/google/apps/chat_v1/types/annotation.py b/packages/google-apps-chat/google/apps/chat_v1/types/annotation.py index baaf7b3dd2f7..bdbe3ea2d6f9 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/types/annotation.py +++ b/packages/google-apps-chat/google/apps/chat_v1/types/annotation.py @@ -311,6 +311,12 @@ class RichLinkType(proto.Enum): CHAT_SPACE (2): A Chat space rich link type. For example, a space smart chip. + GMAIL_MESSAGE (3): + A Gmail message rich link type. Specifically, a Gmail chip + from `Share to + Chat `__. The + API only supports reading messages with GMAIL_MESSAGE rich + links. MEET_SPACE (4): A Meet message rich link type. For example, a Meet chip. @@ -321,6 +327,7 @@ class RichLinkType(proto.Enum): RICH_LINK_TYPE_UNSPECIFIED = 0 DRIVE_FILE = 1 CHAT_SPACE = 2 + GMAIL_MESSAGE = 3 MEET_SPACE = 4 CALENDAR_EVENT = 5 diff --git a/packages/google-apps-chat/google/apps/chat_v1/types/attachment.py b/packages/google-apps-chat/google/apps/chat_v1/types/attachment.py index 666795c918c7..e412a68b54ad 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/types/attachment.py +++ b/packages/google-apps-chat/google/apps/chat_v1/types/attachment.py @@ -44,7 +44,9 @@ class Attachment(proto.Message): Attributes: name (str): - Optional. Resource name of the attachment, in the form + Identifier. Resource name of the attachment. + + Format: ``spaces/{space}/messages/{message}/attachments/{attachment}``. content_name (str): Output only. The original file name for the diff --git a/packages/google-apps-chat/google/apps/chat_v1/types/event_payload.py b/packages/google-apps-chat/google/apps/chat_v1/types/event_payload.py index 0004b33e331c..4132c253a164 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/types/event_payload.py +++ b/packages/google-apps-chat/google/apps/chat_v1/types/event_payload.py @@ -193,9 +193,8 @@ class MessageDeletedEventData(proto.Message): Attributes: message (google.apps.chat_v1.types.Message): - The deleted message. Only the ``name``, ``createTime``, - ``deleteTime``, and ``deletionMetadata`` fields are - populated. + The deleted message. Only the ``name``, ``createTime``, and + ``deletionMetadata`` fields are populated. """ message: gc_message.Message = proto.Field( diff --git a/packages/google-apps-chat/google/apps/chat_v1/types/message.py b/packages/google-apps-chat/google/apps/chat_v1/types/message.py index 6b43cf15deb8..5ef8ae03f642 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/types/message.py +++ b/packages/google-apps-chat/google/apps/chat_v1/types/message.py @@ -135,6 +135,9 @@ class Message(proto.Message): example, ``:smile:``. This doesn't apply to Unicode emoji, such as ``U+1F600`` for a grinning face emoji. + - Bullet list items using asterisks (``*``)—for example, + ``* item``. + For more information, see `View text formatting sent in a message `__ cards (MutableSequence[google.apps.chat_v1.types.ContextualAddOnMarkup.Card]): @@ -223,8 +226,6 @@ class Message(proto.Message): and omit the following: - `Attachments `__ - - `Accessory - widgets `__ For details, see `Send a message privately `__. diff --git a/packages/google-apps-chat/google/apps/chat_v1/types/space.py b/packages/google-apps-chat/google/apps/chat_v1/types/space.py index d0e643e163e0..aeb88d94473d 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/types/space.py +++ b/packages/google-apps-chat/google/apps/chat_v1/types/space.py @@ -166,7 +166,8 @@ class Space(proto.Message): alias to create the space in the same Google Workspace organization as the app. - For DMs, this field isn't populated. + This field isn't populated for direct messages (DMs) or when + the space is created by non-Google Workspace users. This field is a member of `oneof`_ ``_customer``. space_uri (str): @@ -875,8 +876,12 @@ class UpdateSpaceRequest(proto.Message): You can update the following fields for a space: - ``space_details``: Updates the space's description. Supports - up to 150 characters. + ``space_details``: Updates the space's description and + guidelines. You must pass both description and guidelines in + the update request as + [``SpaceDetails``][google.chat.v1.Space.SpaceDetails]. If + you only want to update one of the fields, pass the existing + value for the other field. ``display_name``: Only supports updating the display name for spaces where ``spaceType`` field is ``SPACE``. If you @@ -925,9 +930,8 @@ class UpdateSpaceRequest(proto.Message): settings `__ of a space. When updating permission settings, you can only specify ``permissionSettings`` field masks; you cannot - update other field masks at the same time. - ``permissionSettings`` is not supported with - ``useAdminAccess``. The supported field masks include: + update other field masks at the same time. The supported + field masks include: - ``permission_settings.manageMembersAndGroups`` - ``permission_settings.modifySpaceDetails`` diff --git a/packages/google-apps-chat/tests/unit/gapic/chat_v1/test_chat_service.py b/packages/google-apps-chat/tests/unit/gapic/chat_v1/test_chat_service.py index fbf32997c88e..a0f77452c3ba 100644 --- a/packages/google-apps-chat/tests/unit/gapic/chat_v1/test_chat_service.py +++ b/packages/google-apps-chat/tests/unit/gapic/chat_v1/test_chat_service.py @@ -1299,6 +1299,7 @@ def test_chat_service_client_create_channel_credentials_file( "https://www.googleapis.com/auth/chat.admin.spaces.readonly", "https://www.googleapis.com/auth/chat.app.delete", "https://www.googleapis.com/auth/chat.app.memberships", + "https://www.googleapis.com/auth/chat.app.messages.readonly", "https://www.googleapis.com/auth/chat.app.spaces", "https://www.googleapis.com/auth/chat.app.spaces.create", "https://www.googleapis.com/auth/chat.bot", @@ -29300,6 +29301,7 @@ def test_chat_service_base_transport_with_credentials_file(): "https://www.googleapis.com/auth/chat.admin.spaces.readonly", "https://www.googleapis.com/auth/chat.app.delete", "https://www.googleapis.com/auth/chat.app.memberships", + "https://www.googleapis.com/auth/chat.app.messages.readonly", "https://www.googleapis.com/auth/chat.app.spaces", "https://www.googleapis.com/auth/chat.app.spaces.create", "https://www.googleapis.com/auth/chat.bot", @@ -29353,6 +29355,7 @@ def test_chat_service_auth_adc(): "https://www.googleapis.com/auth/chat.admin.spaces.readonly", "https://www.googleapis.com/auth/chat.app.delete", "https://www.googleapis.com/auth/chat.app.memberships", + "https://www.googleapis.com/auth/chat.app.messages.readonly", "https://www.googleapis.com/auth/chat.app.spaces", "https://www.googleapis.com/auth/chat.app.spaces.create", "https://www.googleapis.com/auth/chat.bot", @@ -29403,6 +29406,7 @@ def test_chat_service_transport_auth_adc(transport_class): "https://www.googleapis.com/auth/chat.admin.spaces.readonly", "https://www.googleapis.com/auth/chat.app.delete", "https://www.googleapis.com/auth/chat.app.memberships", + "https://www.googleapis.com/auth/chat.app.messages.readonly", "https://www.googleapis.com/auth/chat.app.spaces", "https://www.googleapis.com/auth/chat.app.spaces.create", "https://www.googleapis.com/auth/chat.bot", @@ -29485,6 +29489,7 @@ def test_chat_service_transport_create_channel(transport_class, grpc_helpers): "https://www.googleapis.com/auth/chat.admin.spaces.readonly", "https://www.googleapis.com/auth/chat.app.delete", "https://www.googleapis.com/auth/chat.app.memberships", + "https://www.googleapis.com/auth/chat.app.messages.readonly", "https://www.googleapis.com/auth/chat.app.spaces", "https://www.googleapis.com/auth/chat.app.spaces.create", "https://www.googleapis.com/auth/chat.bot", diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/services/alloy_db_admin/async_client.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/services/alloy_db_admin/async_client.py index 9a6fe0b23b01..bacd85a6a946 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/services/alloy_db_admin/async_client.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/services/alloy_db_admin/async_client.py @@ -1255,7 +1255,7 @@ async def sample_upgrade_cluster(): # Initialize request argument(s) request = alloydb_v1beta.UpgradeClusterRequest( name="name_value", - version="POSTGRES_17", + version="POSTGRES_18", ) # Make the request diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/services/alloy_db_admin/client.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/services/alloy_db_admin/client.py index 9198f44f94d5..0c804327b1b8 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/services/alloy_db_admin/client.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/services/alloy_db_admin/client.py @@ -1878,7 +1878,7 @@ def sample_upgrade_cluster(): # Initialize request argument(s) request = alloydb_v1beta.UpgradeClusterRequest( name="name_value", - version="POSTGRES_17", + version="POSTGRES_18", ) # Make the request diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/types/resources.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/types/resources.py index 57af831c16e4..5b4689f7832e 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/types/resources.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/types/resources.py @@ -121,6 +121,8 @@ class DatabaseVersion(proto.Enum): The database version is Postgres 16. POSTGRES_17 (5): The database version is Postgres 17. + POSTGRES_18 (6): + The database version is Postgres 18. """ DATABASE_VERSION_UNSPECIFIED = 0 POSTGRES_13 = 1 @@ -128,6 +130,7 @@ class DatabaseVersion(proto.Enum): POSTGRES_15 = 3 POSTGRES_16 = 4 POSTGRES_17 = 5 + POSTGRES_18 = 6 class SubscriptionType(proto.Enum): diff --git a/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_upgrade_cluster_async.py b/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_upgrade_cluster_async.py index 52efa232255e..df8bb2e6b8ce 100644 --- a/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_upgrade_cluster_async.py +++ b/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_upgrade_cluster_async.py @@ -41,7 +41,7 @@ async def sample_upgrade_cluster(): # Initialize request argument(s) request = alloydb_v1beta.UpgradeClusterRequest( name="name_value", - version="POSTGRES_17", + version="POSTGRES_18", ) # Make the request diff --git a/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_upgrade_cluster_sync.py b/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_upgrade_cluster_sync.py index c196fb5f7a4e..cdb955f0f8d9 100644 --- a/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_upgrade_cluster_sync.py +++ b/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1beta_generated_alloy_db_admin_upgrade_cluster_sync.py @@ -41,7 +41,7 @@ def sample_upgrade_cluster(): # Initialize request argument(s) request = alloydb_v1beta.UpgradeClusterRequest( name="name_value", - version="POSTGRES_17", + version="POSTGRES_18", ) # Make the request diff --git a/packages/google-cloud-artifact-registry/google/cloud/artifactregistry_v1/services/artifact_registry/async_client.py b/packages/google-cloud-artifact-registry/google/cloud/artifactregistry_v1/services/artifact_registry/async_client.py index a9848db8fbe6..12614d55839f 100644 --- a/packages/google-cloud-artifact-registry/google/cloud/artifactregistry_v1/services/artifact_registry/async_client.py +++ b/packages/google-cloud-artifact-registry/google/cloud/artifactregistry_v1/services/artifact_registry/async_client.py @@ -6287,7 +6287,7 @@ async def export_artifact( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation_async.AsyncOperation: - r"""Exports an artifact. + r"""Exports an artifact to a Cloud Storage bucket. .. code-block:: python diff --git a/packages/google-cloud-artifact-registry/google/cloud/artifactregistry_v1/services/artifact_registry/client.py b/packages/google-cloud-artifact-registry/google/cloud/artifactregistry_v1/services/artifact_registry/client.py index 4646053cede3..d8e9ddb023de 100644 --- a/packages/google-cloud-artifact-registry/google/cloud/artifactregistry_v1/services/artifact_registry/client.py +++ b/packages/google-cloud-artifact-registry/google/cloud/artifactregistry_v1/services/artifact_registry/client.py @@ -6900,7 +6900,7 @@ def export_artifact( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operation.Operation: - r"""Exports an artifact. + r"""Exports an artifact to a Cloud Storage bucket. .. code-block:: python diff --git a/packages/google-cloud-artifact-registry/google/cloud/artifactregistry_v1/services/artifact_registry/transports/grpc.py b/packages/google-cloud-artifact-registry/google/cloud/artifactregistry_v1/services/artifact_registry/transports/grpc.py index 1db957b7e39c..6c121c1d8004 100644 --- a/packages/google-cloud-artifact-registry/google/cloud/artifactregistry_v1/services/artifact_registry/transports/grpc.py +++ b/packages/google-cloud-artifact-registry/google/cloud/artifactregistry_v1/services/artifact_registry/transports/grpc.py @@ -1665,7 +1665,7 @@ def export_artifact( ) -> Callable[[export.ExportArtifactRequest], operations_pb2.Operation]: r"""Return a callable for the export artifact method over gRPC. - Exports an artifact. + Exports an artifact to a Cloud Storage bucket. Returns: Callable[[~.ExportArtifactRequest], diff --git a/packages/google-cloud-artifact-registry/google/cloud/artifactregistry_v1/services/artifact_registry/transports/grpc_asyncio.py b/packages/google-cloud-artifact-registry/google/cloud/artifactregistry_v1/services/artifact_registry/transports/grpc_asyncio.py index 29b25b12e36e..45bfe2f6e6e5 100644 --- a/packages/google-cloud-artifact-registry/google/cloud/artifactregistry_v1/services/artifact_registry/transports/grpc_asyncio.py +++ b/packages/google-cloud-artifact-registry/google/cloud/artifactregistry_v1/services/artifact_registry/transports/grpc_asyncio.py @@ -1734,7 +1734,7 @@ def export_artifact( ) -> Callable[[export.ExportArtifactRequest], Awaitable[operations_pb2.Operation]]: r"""Return a callable for the export artifact method over gRPC. - Exports an artifact. + Exports an artifact to a Cloud Storage bucket. Returns: Callable[[~.ExportArtifactRequest], diff --git a/packages/google-cloud-artifact-registry/google/cloud/artifactregistry_v1/types/version.py b/packages/google-cloud-artifact-registry/google/cloud/artifactregistry_v1/types/version.py index 104f5fdd71de..9ca0909f4592 100644 --- a/packages/google-cloud-artifact-registry/google/cloud/artifactregistry_v1/types/version.py +++ b/packages/google-cloud-artifact-registry/google/cloud/artifactregistry_v1/types/version.py @@ -22,7 +22,7 @@ from google.protobuf import timestamp_pb2 # type: ignore import proto # type: ignore -from google.cloud.artifactregistry_v1.types import tag +from google.cloud.artifactregistry_v1.types import file, tag __protobuf__ = proto.module( package="google.devtools.artifactregistry.v1", @@ -90,6 +90,11 @@ class Version(proto.Message): [MavenArtifact][google.devtools.artifactregistry.v1.MavenArtifact] annotations (MutableMapping[str, str]): Optional. Client specified annotations. + fingerprints (MutableSequence[google.cloud.artifactregistry_v1.types.Hash]): + Output only. Immutable reference for the version, calculated + based on the version's content. Currently we only support + dirsum_sha256 hash algorithm. Additional hash algorithms may + be added in the future. """ name: str = proto.Field( @@ -125,6 +130,11 @@ class Version(proto.Message): proto.STRING, number=9, ) + fingerprints: MutableSequence[file.Hash] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message=file.Hash, + ) class ListVersionsRequest(proto.Message): diff --git a/packages/google-cloud-artifact-registry/tests/unit/gapic/artifactregistry_v1/test_artifact_registry.py b/packages/google-cloud-artifact-registry/tests/unit/gapic/artifactregistry_v1/test_artifact_registry.py index 05837f24ee75..c7bd2d76f3c3 100644 --- a/packages/google-cloud-artifact-registry/tests/unit/gapic/artifactregistry_v1/test_artifact_registry.py +++ b/packages/google-cloud-artifact-registry/tests/unit/gapic/artifactregistry_v1/test_artifact_registry.py @@ -34328,6 +34328,7 @@ def test_update_version_rest_call_success(request_type): "related_tags": [{"name": "name_value", "version": "version_value"}], "metadata": {"fields": {}}, "annotations": {}, + "fingerprints": [{"type_": 1, "value": b"value_blob"}], } # 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 diff --git a/packages/google-cloud-build/google/cloud/devtools/cloudbuild_v1/types/cloudbuild.py b/packages/google-cloud-build/google/cloud/devtools/cloudbuild_v1/types/cloudbuild.py index de4a292e4a60..a67a8ce56ac5 100644 --- a/packages/google-cloud-build/google/cloud/devtools/cloudbuild_v1/types/cloudbuild.py +++ b/packages/google-cloud-build/google/cloud/devtools/cloudbuild_v1/types/cloudbuild.py @@ -125,7 +125,7 @@ class DefaultServiceAccount(proto.Message): Attributes: name (str): Identifier. Format: - \`projects/{project}/locations/{location}/defaultServiceAccount + ``projects/{project}/locations/{location}/defaultServiceAccount`` service_account_email (str): Output only. The email address of the service account identity that will be used for a build by default. diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/__init__.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/__init__.py index 2e55672e08b1..70c228658e6b 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/__init__.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/__init__.py @@ -290,6 +290,7 @@ CloudConversationDebuggingInfo, DetectIntentRequest, DetectIntentResponse, + DetectIntentResponseView, DtmfInput, EventInput, FilterSpecs, @@ -630,6 +631,7 @@ def _get_version(dependency_name): "DeploymentsClient", "DetectIntentRequest", "DetectIntentResponse", + "DetectIntentResponseView", "DocumentProcessingMode", "DtmfInput", "EntityType", diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/types/__init__.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/types/__init__.py index 33f5fcdb82d7..ea9e527b8595 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/types/__init__.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/types/__init__.py @@ -242,6 +242,7 @@ CloudConversationDebuggingInfo, DetectIntentRequest, DetectIntentResponse, + DetectIntentResponseView, DtmfInput, EventInput, FilterSpecs, @@ -604,6 +605,7 @@ "StreamingRecognitionResult", "SubmitAnswerFeedbackRequest", "TextInput", + "DetectIntentResponseView", "CreateSessionEntityTypeRequest", "DeleteSessionEntityTypeRequest", "GetSessionEntityTypeRequest", diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/types/safety_settings.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/types/safety_settings.py index a320229b51aa..298d71019785 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/types/safety_settings.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/types/safety_settings.py @@ -36,6 +36,14 @@ class SafetySettings(proto.Message): banned phrases. banned_phrases (MutableSequence[google.cloud.dialogflowcx_v3beta1.types.SafetySettings.Phrase]): Banned phrases for generated text. + rai_settings (google.cloud.dialogflowcx_v3beta1.types.SafetySettings.RaiSettings): + Optional. Settings for Responsible AI checks. + default_rai_settings (google.cloud.dialogflowcx_v3beta1.types.SafetySettings.RaiSettings): + Optional. Immutable. Default RAI settings to + be annotated on the agent, so that users will be + able to restore their RAI configurations to the + default settings. Read-only field for the API + proto only. prompt_security_settings (google.cloud.dialogflowcx_v3beta1.types.SafetySettings.PromptSecuritySettings): Optional. Settings for prompt security checks. @@ -80,6 +88,89 @@ class Phrase(proto.Message): number=2, ) + class RaiSettings(proto.Message): + r"""Settings for Responsible AI. + + Attributes: + category_filters (MutableSequence[google.cloud.dialogflowcx_v3beta1.types.SafetySettings.RaiSettings.CategoryFilter]): + Optional. RAI blocking configurations. + """ + + class SafetyFilterLevel(proto.Enum): + r"""Sensitivity level for RAI categories. + + Values: + SAFETY_FILTER_LEVEL_UNSPECIFIED (0): + Unspecified -- uses default sensitivity + levels. + BLOCK_NONE (1): + Block no text -- effectively disables the + category. + BLOCK_FEW (2): + Block a few suspicious texts. + BLOCK_SOME (3): + Block some suspicious texts. + BLOCK_MOST (4): + Block most suspicious texts. + """ + SAFETY_FILTER_LEVEL_UNSPECIFIED = 0 + BLOCK_NONE = 1 + BLOCK_FEW = 2 + BLOCK_SOME = 3 + BLOCK_MOST = 4 + + class SafetyCategory(proto.Enum): + r"""RAI categories to configure. + + Values: + SAFETY_CATEGORY_UNSPECIFIED (0): + Unspecified. + DANGEROUS_CONTENT (1): + Dangerous content. + HATE_SPEECH (2): + Hate speech. + HARASSMENT (3): + Harassment. + SEXUALLY_EXPLICIT_CONTENT (4): + Sexually explicit content. + """ + SAFETY_CATEGORY_UNSPECIFIED = 0 + DANGEROUS_CONTENT = 1 + HATE_SPEECH = 2 + HARASSMENT = 3 + SEXUALLY_EXPLICIT_CONTENT = 4 + + class CategoryFilter(proto.Message): + r"""Configuration of the sensitivity level for blocking an RAI + category. + + Attributes: + category (google.cloud.dialogflowcx_v3beta1.types.SafetySettings.RaiSettings.SafetyCategory): + RAI category to configure. + filter_level (google.cloud.dialogflowcx_v3beta1.types.SafetySettings.RaiSettings.SafetyFilterLevel): + Blocking sensitivity level to configure for + the RAI category. + """ + + category: "SafetySettings.RaiSettings.SafetyCategory" = proto.Field( + proto.ENUM, + number=1, + enum="SafetySettings.RaiSettings.SafetyCategory", + ) + filter_level: "SafetySettings.RaiSettings.SafetyFilterLevel" = proto.Field( + proto.ENUM, + number=2, + enum="SafetySettings.RaiSettings.SafetyFilterLevel", + ) + + category_filters: MutableSequence[ + "SafetySettings.RaiSettings.CategoryFilter" + ] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="SafetySettings.RaiSettings.CategoryFilter", + ) + class PromptSecuritySettings(proto.Message): r"""Settings for prompt security checks. @@ -103,6 +194,16 @@ class PromptSecuritySettings(proto.Message): number=1, message=Phrase, ) + rai_settings: RaiSettings = proto.Field( + proto.MESSAGE, + number=2, + message=RaiSettings, + ) + default_rai_settings: RaiSettings = proto.Field( + proto.MESSAGE, + number=3, + message=RaiSettings, + ) prompt_security_settings: PromptSecuritySettings = proto.Field( proto.MESSAGE, number=8, diff --git a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/types/session.py b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/types/session.py index b88c2206bf38..22ffe5c3a563 100644 --- a/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/types/session.py +++ b/packages/google-cloud-dialogflow-cx/google/cloud/dialogflowcx_v3beta1/types/session.py @@ -45,6 +45,7 @@ __protobuf__ = proto.module( package="google.cloud.dialogflow.cx.v3beta1", manifest={ + "DetectIntentResponseView", "AnswerFeedback", "SubmitAnswerFeedbackRequest", "DetectIntentRequest", @@ -76,6 +77,30 @@ ) +class DetectIntentResponseView(proto.Enum): + r"""The response view specifies which fields in the + [QueryResult][google.cloud.dialogflow.cx.v3beta1.QueryResult] to + return. + + Values: + DETECT_INTENT_RESPONSE_VIEW_UNSPECIFIED (0): + Not specified. ``FULL`` will be used. + DETECT_INTENT_RESPONSE_VIEW_FULL (1): + Full response view includes all fields. + DETECT_INTENT_RESPONSE_VIEW_BASIC (2): + Basic response view omits the following fields: + ----------------------------------------------- + + [QueryResult.diagnostic_info][google.cloud.dialogflow.cx.v3beta1.QueryResult.diagnostic_info] + --------------------------------------------------------------------------------------------- + + [QueryResult.generative_info][google.cloud.dialogflow.cx.v3beta1.QueryResult.generative_info] + """ + DETECT_INTENT_RESPONSE_VIEW_UNSPECIFIED = 0 + DETECT_INTENT_RESPONSE_VIEW_FULL = 1 + DETECT_INTENT_RESPONSE_VIEW_BASIC = 2 + + class AnswerFeedback(proto.Message): r"""Stores information about feedback provided by users about a response. @@ -218,6 +243,11 @@ class DetectIntentRequest(proto.Message): output_audio_config (google.cloud.dialogflowcx_v3beta1.types.OutputAudioConfig): Instructs the speech synthesizer how to generate the output audio. + response_view (google.cloud.dialogflowcx_v3beta1.types.DetectIntentResponseView): + Optional. Specifies which fields in the + [QueryResult][google.cloud.dialogflow.cx.v3beta1.QueryResult] + to return. If not set, the default is + DETECT_INTENT_RESPONSE_VIEW_FULL. """ session: str = proto.Field( @@ -239,6 +269,11 @@ class DetectIntentRequest(proto.Message): number=4, message=audio_config.OutputAudioConfig, ) + response_view: "DetectIntentResponseView" = proto.Field( + proto.ENUM, + number=9, + enum="DetectIntentResponseView", + ) class DetectIntentResponse(proto.Message): @@ -395,6 +430,11 @@ class StreamingDetectIntentRequest(proto.Message): enable_debugging_info (bool): If true, ``StreamingDetectIntentResponse.debugging_info`` will get populated. + response_view (google.cloud.dialogflowcx_v3beta1.types.DetectIntentResponseView): + Optional. Specifies which fields in the + [QueryResult][google.cloud.dialogflow.cx.v3beta1.QueryResult] + to return. If not set, the default is + DETECT_INTENT_RESPONSE_VIEW_FULL. """ session: str = proto.Field( @@ -424,6 +464,11 @@ class StreamingDetectIntentRequest(proto.Message): proto.BOOL, number=8, ) + response_view: "DetectIntentResponseView" = proto.Field( + proto.ENUM, + number=16, + enum="DetectIntentResponseView", + ) class CloudConversationDebuggingInfo(proto.Message): diff --git a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_agents.py b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_agents.py index d3e819f4155c..01eb23fa2678 100644 --- a/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_agents.py +++ b/packages/google-cloud-dialogflow-cx/tests/unit/gapic/dialogflowcx_v3beta1/test_agents.py @@ -9280,6 +9280,8 @@ def test_update_generative_settings_rest_call_success(request_type): "banned_phrases": [ {"text": "text_value", "language_code": "language_code_value"} ], + "rai_settings": {"category_filters": [{"category": 1, "filter_level": 1}]}, + "default_rai_settings": {}, "prompt_security_settings": {"enable_prompt_security": True}, }, "knowledge_connector_settings": { diff --git a/packages/google-cloud-dialogflow/docs/dialogflow_v2/generator_evaluations.rst b/packages/google-cloud-dialogflow/docs/dialogflow_v2/generator_evaluations.rst new file mode 100644 index 000000000000..f766fa9b754e --- /dev/null +++ b/packages/google-cloud-dialogflow/docs/dialogflow_v2/generator_evaluations.rst @@ -0,0 +1,10 @@ +GeneratorEvaluations +-------------------------------------- + +.. automodule:: google.cloud.dialogflow_v2.services.generator_evaluations + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflow_v2.services.generator_evaluations.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-dialogflow/docs/dialogflow_v2/services_.rst b/packages/google-cloud-dialogflow/docs/dialogflow_v2/services_.rst index 5bdf1deb9d22..22d7fba84b66 100644 --- a/packages/google-cloud-dialogflow/docs/dialogflow_v2/services_.rst +++ b/packages/google-cloud-dialogflow/docs/dialogflow_v2/services_.rst @@ -15,10 +15,13 @@ Services for Google Cloud Dialogflow v2 API entity_types environments fulfillments + generator_evaluations generators intents knowledge_bases participants session_entity_types sessions + sip_trunks + tools versions diff --git a/packages/google-cloud-dialogflow/docs/dialogflow_v2/sip_trunks.rst b/packages/google-cloud-dialogflow/docs/dialogflow_v2/sip_trunks.rst new file mode 100644 index 000000000000..5aa8cf706787 --- /dev/null +++ b/packages/google-cloud-dialogflow/docs/dialogflow_v2/sip_trunks.rst @@ -0,0 +1,10 @@ +SipTrunks +--------------------------- + +.. automodule:: google.cloud.dialogflow_v2.services.sip_trunks + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflow_v2.services.sip_trunks.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-dialogflow/docs/dialogflow_v2/tools.rst b/packages/google-cloud-dialogflow/docs/dialogflow_v2/tools.rst new file mode 100644 index 000000000000..be2e64004026 --- /dev/null +++ b/packages/google-cloud-dialogflow/docs/dialogflow_v2/tools.rst @@ -0,0 +1,10 @@ +Tools +----------------------- + +.. automodule:: google.cloud.dialogflow_v2.services.tools + :members: + :inherited-members: + +.. automodule:: google.cloud.dialogflow_v2.services.tools.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow/__init__.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow/__init__.py index aff28e43bf18..df8571957553 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow/__init__.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow/__init__.py @@ -74,6 +74,12 @@ FulfillmentsAsyncClient, ) from google.cloud.dialogflow_v2.services.fulfillments.client import FulfillmentsClient +from google.cloud.dialogflow_v2.services.generator_evaluations.async_client import ( + GeneratorEvaluationsAsyncClient, +) +from google.cloud.dialogflow_v2.services.generator_evaluations.client import ( + GeneratorEvaluationsClient, +) from google.cloud.dialogflow_v2.services.generators.async_client import ( GeneratorsAsyncClient, ) @@ -100,6 +106,12 @@ SessionsAsyncClient, ) from google.cloud.dialogflow_v2.services.sessions.client import SessionsClient +from google.cloud.dialogflow_v2.services.sip_trunks.async_client import ( + SipTrunksAsyncClient, +) +from google.cloud.dialogflow_v2.services.sip_trunks.client import SipTrunksClient +from google.cloud.dialogflow_v2.services.tools.async_client import ToolsAsyncClient +from google.cloud.dialogflow_v2.services.tools.client import ToolsClient from google.cloud.dialogflow_v2.services.versions.async_client import ( VersionsAsyncClient, ) @@ -118,6 +130,9 @@ SetAgentRequest, TrainAgentRequest, ) +from google.cloud.dialogflow_v2.types.agent_coaching_instruction import ( + AgentCoachingInstruction, +) from google.cloud.dialogflow_v2.types.answer_record import ( AgentAssistantFeedback, AgentAssistantRecord, @@ -129,6 +144,7 @@ ) from google.cloud.dialogflow_v2.types.audio_config import ( AudioEncoding, + CustomPronunciationParams, InputAudioConfig, OutputAudioConfig, OutputAudioEncoding, @@ -293,6 +309,8 @@ ) from google.cloud.dialogflow_v2.types.gcs import GcsDestination, GcsSources from google.cloud.dialogflow_v2.types.generator import ( + AgentCoachingContext, + AgentCoachingSuggestion, ConversationContext, CreateGeneratorRequest, DeleteGeneratorRequest, @@ -306,6 +324,8 @@ ListGeneratorsRequest, ListGeneratorsResponse, MessageEntry, + RaiSettings, + SuggestionDedupingConfig, SummarizationContext, SummarizationSection, SummarizationSectionList, @@ -313,6 +333,17 @@ TriggerEvent, UpdateGeneratorRequest, ) +from google.cloud.dialogflow_v2.types.generator_evaluation import ( + CreateGeneratorEvaluationRequest, + DeleteGeneratorEvaluationRequest, + EvaluationStatus, + GeneratorEvaluation, + GeneratorEvaluationConfig, + GetGeneratorEvaluationRequest, + ListGeneratorEvaluationsRequest, + ListGeneratorEvaluationsResponse, + SummarizationEvaluationMetrics, +) from google.cloud.dialogflow_v2.types.human_agent_assistant_event import ( HumanAgentAssistantEvent, ) @@ -339,6 +370,9 @@ ListKnowledgeBasesResponse, UpdateKnowledgeBaseRequest, ) +from google.cloud.dialogflow_v2.types.operations import ( + GeneratorEvaluationOperationMetadata, +) from google.cloud.dialogflow_v2.types.participant import ( AnalyzeContentRequest, AnalyzeContentResponse, @@ -402,6 +436,26 @@ SessionEntityType, UpdateSessionEntityTypeRequest, ) +from google.cloud.dialogflow_v2.types.sip_trunk import ( + Connection, + CreateSipTrunkRequest, + DeleteSipTrunkRequest, + GetSipTrunkRequest, + ListSipTrunksRequest, + ListSipTrunksResponse, + SipTrunk, + UpdateSipTrunkRequest, +) +from google.cloud.dialogflow_v2.types.tool import ( + CreateToolRequest, + DeleteToolRequest, + GetToolRequest, + ListToolsRequest, + ListToolsResponse, + Tool, + UpdateToolRequest, +) +from google.cloud.dialogflow_v2.types.tool_call import ToolCall, ToolCallResult from google.cloud.dialogflow_v2.types.validation_result import ( ValidationError, ValidationResult, @@ -446,6 +500,8 @@ "EnvironmentsAsyncClient", "FulfillmentsClient", "FulfillmentsAsyncClient", + "GeneratorEvaluationsClient", + "GeneratorEvaluationsAsyncClient", "GeneratorsClient", "GeneratorsAsyncClient", "IntentsClient", @@ -458,6 +514,10 @@ "SessionEntityTypesAsyncClient", "SessionsClient", "SessionsAsyncClient", + "SipTrunksClient", + "SipTrunksAsyncClient", + "ToolsClient", + "ToolsAsyncClient", "VersionsClient", "VersionsAsyncClient", "Agent", @@ -472,6 +532,7 @@ "SearchAgentsResponse", "SetAgentRequest", "TrainAgentRequest", + "AgentCoachingInstruction", "AgentAssistantFeedback", "AgentAssistantRecord", "AnswerFeedback", @@ -479,6 +540,7 @@ "ListAnswerRecordsRequest", "ListAnswerRecordsResponse", "UpdateAnswerRecordRequest", + "CustomPronunciationParams", "InputAudioConfig", "OutputAudioConfig", "SpeechContext", @@ -623,6 +685,8 @@ "UpdateFulfillmentRequest", "GcsDestination", "GcsSources", + "AgentCoachingContext", + "AgentCoachingSuggestion", "ConversationContext", "CreateGeneratorRequest", "DeleteGeneratorRequest", @@ -636,12 +700,23 @@ "ListGeneratorsRequest", "ListGeneratorsResponse", "MessageEntry", + "RaiSettings", + "SuggestionDedupingConfig", "SummarizationContext", "SummarizationSection", "SummarizationSectionList", "SummarySuggestion", "UpdateGeneratorRequest", "TriggerEvent", + "CreateGeneratorEvaluationRequest", + "DeleteGeneratorEvaluationRequest", + "EvaluationStatus", + "GeneratorEvaluation", + "GeneratorEvaluationConfig", + "GetGeneratorEvaluationRequest", + "ListGeneratorEvaluationsRequest", + "ListGeneratorEvaluationsResponse", + "SummarizationEvaluationMetrics", "HumanAgentAssistantEvent", "BatchDeleteIntentsRequest", "BatchUpdateIntentsRequest", @@ -662,6 +737,7 @@ "ListKnowledgeBasesRequest", "ListKnowledgeBasesResponse", "UpdateKnowledgeBaseRequest", + "GeneratorEvaluationOperationMetadata", "AnalyzeContentRequest", "AnalyzeContentResponse", "AnnotatedMessagePart", @@ -719,6 +795,23 @@ "ListSessionEntityTypesResponse", "SessionEntityType", "UpdateSessionEntityTypeRequest", + "Connection", + "CreateSipTrunkRequest", + "DeleteSipTrunkRequest", + "GetSipTrunkRequest", + "ListSipTrunksRequest", + "ListSipTrunksResponse", + "SipTrunk", + "UpdateSipTrunkRequest", + "CreateToolRequest", + "DeleteToolRequest", + "GetToolRequest", + "ListToolsRequest", + "ListToolsResponse", + "Tool", + "UpdateToolRequest", + "ToolCall", + "ToolCallResult", "ValidationError", "ValidationResult", "CreateVersionRequest", diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/__init__.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/__init__.py index a923e82673d0..157877f25793 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/__init__.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/__init__.py @@ -52,6 +52,10 @@ from .services.entity_types import EntityTypesAsyncClient, EntityTypesClient from .services.environments import EnvironmentsAsyncClient, EnvironmentsClient from .services.fulfillments import FulfillmentsAsyncClient, FulfillmentsClient +from .services.generator_evaluations import ( + GeneratorEvaluationsAsyncClient, + GeneratorEvaluationsClient, +) from .services.generators import GeneratorsAsyncClient, GeneratorsClient from .services.intents import IntentsAsyncClient, IntentsClient from .services.knowledge_bases import KnowledgeBasesAsyncClient, KnowledgeBasesClient @@ -61,6 +65,8 @@ SessionEntityTypesClient, ) from .services.sessions import SessionsAsyncClient, SessionsClient +from .services.sip_trunks import SipTrunksAsyncClient, SipTrunksClient +from .services.tools import ToolsAsyncClient, ToolsClient from .services.versions import VersionsAsyncClient, VersionsClient from .types.agent import ( Agent, @@ -76,6 +82,7 @@ SetAgentRequest, TrainAgentRequest, ) +from .types.agent_coaching_instruction import AgentCoachingInstruction from .types.answer_record import ( AgentAssistantFeedback, AgentAssistantRecord, @@ -87,6 +94,7 @@ ) from .types.audio_config import ( AudioEncoding, + CustomPronunciationParams, InputAudioConfig, OutputAudioConfig, OutputAudioEncoding, @@ -251,6 +259,8 @@ ) from .types.gcs import GcsDestination, GcsSources from .types.generator import ( + AgentCoachingContext, + AgentCoachingSuggestion, ConversationContext, CreateGeneratorRequest, DeleteGeneratorRequest, @@ -264,6 +274,8 @@ ListGeneratorsRequest, ListGeneratorsResponse, MessageEntry, + RaiSettings, + SuggestionDedupingConfig, SummarizationContext, SummarizationSection, SummarizationSectionList, @@ -271,6 +283,17 @@ TriggerEvent, UpdateGeneratorRequest, ) +from .types.generator_evaluation import ( + CreateGeneratorEvaluationRequest, + DeleteGeneratorEvaluationRequest, + EvaluationStatus, + GeneratorEvaluation, + GeneratorEvaluationConfig, + GetGeneratorEvaluationRequest, + ListGeneratorEvaluationsRequest, + ListGeneratorEvaluationsResponse, + SummarizationEvaluationMetrics, +) from .types.human_agent_assistant_event import HumanAgentAssistantEvent from .types.intent import ( BatchDeleteIntentsRequest, @@ -295,6 +318,7 @@ ListKnowledgeBasesResponse, UpdateKnowledgeBaseRequest, ) +from .types.operations import GeneratorEvaluationOperationMetadata from .types.participant import ( AnalyzeContentRequest, AnalyzeContentResponse, @@ -358,6 +382,26 @@ SessionEntityType, UpdateSessionEntityTypeRequest, ) +from .types.sip_trunk import ( + Connection, + CreateSipTrunkRequest, + DeleteSipTrunkRequest, + GetSipTrunkRequest, + ListSipTrunksRequest, + ListSipTrunksResponse, + SipTrunk, + UpdateSipTrunkRequest, +) +from .types.tool import ( + CreateToolRequest, + DeleteToolRequest, + GetToolRequest, + ListToolsRequest, + ListToolsResponse, + Tool, + UpdateToolRequest, +) +from .types.tool_call import ToolCall, ToolCallResult from .types.validation_result import ValidationError, ValidationResult from .types.version import ( CreateVersionRequest, @@ -477,16 +521,22 @@ def _get_version(dependency_name): "EntityTypesAsyncClient", "EnvironmentsAsyncClient", "FulfillmentsAsyncClient", + "GeneratorEvaluationsAsyncClient", "GeneratorsAsyncClient", "IntentsAsyncClient", "KnowledgeBasesAsyncClient", "ParticipantsAsyncClient", "SessionEntityTypesAsyncClient", "SessionsAsyncClient", + "SipTrunksAsyncClient", + "ToolsAsyncClient", "VersionsAsyncClient", "Agent", "AgentAssistantFeedback", "AgentAssistantRecord", + "AgentCoachingContext", + "AgentCoachingInstruction", + "AgentCoachingSuggestion", "AgentsClient", "AnalyzeContentRequest", "AnalyzeContentResponse", @@ -514,6 +564,7 @@ def _get_version(dependency_name): "ClearSuggestionFeatureConfigRequest", "CloudConversationDebuggingInfo", "CompleteConversationRequest", + "Connection", "Context", "ContextsClient", "Conversation", @@ -541,12 +592,16 @@ def _get_version(dependency_name): "CreateDocumentRequest", "CreateEntityTypeRequest", "CreateEnvironmentRequest", + "CreateGeneratorEvaluationRequest", "CreateGeneratorRequest", "CreateIntentRequest", "CreateKnowledgeBaseRequest", "CreateParticipantRequest", "CreateSessionEntityTypeRequest", + "CreateSipTrunkRequest", + "CreateToolRequest", "CreateVersionRequest", + "CustomPronunciationParams", "DeleteAgentRequest", "DeleteAllContextsRequest", "DeleteContextRequest", @@ -558,10 +613,13 @@ def _get_version(dependency_name): "DeleteDocumentRequest", "DeleteEntityTypeRequest", "DeleteEnvironmentRequest", + "DeleteGeneratorEvaluationRequest", "DeleteGeneratorRequest", "DeleteIntentRequest", "DeleteKnowledgeBaseRequest", "DeleteSessionEntityTypeRequest", + "DeleteSipTrunkRequest", + "DeleteToolRequest", "DeleteVersionRequest", "DeployConversationModelOperationMetadata", "DeployConversationModelRequest", @@ -580,6 +638,7 @@ def _get_version(dependency_name): "EnvironmentHistory", "EnvironmentsClient", "EvaluationConfig", + "EvaluationStatus", "EventInput", "ExportAgentRequest", "ExportAgentResponse", @@ -600,6 +659,10 @@ def _get_version(dependency_name): "GenerateSuggestionsRequest", "GenerateSuggestionsResponse", "Generator", + "GeneratorEvaluation", + "GeneratorEvaluationConfig", + "GeneratorEvaluationOperationMetadata", + "GeneratorEvaluationsClient", "GeneratorSuggestion", "GeneratorsClient", "GetAgentRequest", @@ -615,11 +678,14 @@ def _get_version(dependency_name): "GetEnvironmentHistoryRequest", "GetEnvironmentRequest", "GetFulfillmentRequest", + "GetGeneratorEvaluationRequest", "GetGeneratorRequest", "GetIntentRequest", "GetKnowledgeBaseRequest", "GetParticipantRequest", "GetSessionEntityTypeRequest", + "GetSipTrunkRequest", + "GetToolRequest", "GetValidationResultRequest", "GetVersionRequest", "HumanAgentAssistantConfig", @@ -671,6 +737,8 @@ def _get_version(dependency_name): "ListEntityTypesResponse", "ListEnvironmentsRequest", "ListEnvironmentsResponse", + "ListGeneratorEvaluationsRequest", + "ListGeneratorEvaluationsResponse", "ListGeneratorsRequest", "ListGeneratorsResponse", "ListIntentsRequest", @@ -683,6 +751,10 @@ def _get_version(dependency_name): "ListParticipantsResponse", "ListSessionEntityTypesRequest", "ListSessionEntityTypesResponse", + "ListSipTrunksRequest", + "ListSipTrunksResponse", + "ListToolsRequest", + "ListToolsResponse", "ListVersionsRequest", "ListVersionsResponse", "LoggingConfig", @@ -699,6 +771,7 @@ def _get_version(dependency_name): "QueryInput", "QueryParameters", "QueryResult", + "RaiSettings", "ReloadDocumentRequest", "RestoreAgentRequest", "SearchAgentsRequest", @@ -715,6 +788,8 @@ def _get_version(dependency_name): "SetAgentRequest", "SetSuggestionFeatureConfigOperationMetadata", "SetSuggestionFeatureConfigRequest", + "SipTrunk", + "SipTrunksClient", "SmartReplyAnswer", "SmartReplyMetrics", "SmartReplyModelMetadata", @@ -738,10 +813,12 @@ def _get_version(dependency_name): "SuggestKnowledgeAssistResponse", "SuggestSmartRepliesRequest", "SuggestSmartRepliesResponse", + "SuggestionDedupingConfig", "SuggestionFeature", "SuggestionInput", "SuggestionResult", "SummarizationContext", + "SummarizationEvaluationMetrics", "SummarizationSection", "SummarizationSectionList", "SummarySuggestion", @@ -750,6 +827,10 @@ def _get_version(dependency_name): "TelephonyDtmfEvents", "TextInput", "TextToSpeechSettings", + "Tool", + "ToolCall", + "ToolCallResult", + "ToolsClient", "TrainAgentRequest", "TriggerEvent", "UndeployConversationModelOperationMetadata", @@ -766,6 +847,8 @@ def _get_version(dependency_name): "UpdateKnowledgeBaseRequest", "UpdateParticipantRequest", "UpdateSessionEntityTypeRequest", + "UpdateSipTrunkRequest", + "UpdateToolRequest", "UpdateVersionRequest", "ValidationError", "ValidationResult", diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/gapic_metadata.json b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/gapic_metadata.json index bc8b57529cc9..358fd29a9b20 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/gapic_metadata.json +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/gapic_metadata.json @@ -1388,6 +1388,85 @@ } } }, + "GeneratorEvaluations": { + "clients": { + "grpc": { + "libraryClient": "GeneratorEvaluationsClient", + "rpcs": { + "CreateGeneratorEvaluation": { + "methods": [ + "create_generator_evaluation" + ] + }, + "DeleteGeneratorEvaluation": { + "methods": [ + "delete_generator_evaluation" + ] + }, + "GetGeneratorEvaluation": { + "methods": [ + "get_generator_evaluation" + ] + }, + "ListGeneratorEvaluations": { + "methods": [ + "list_generator_evaluations" + ] + } + } + }, + "grpc-async": { + "libraryClient": "GeneratorEvaluationsAsyncClient", + "rpcs": { + "CreateGeneratorEvaluation": { + "methods": [ + "create_generator_evaluation" + ] + }, + "DeleteGeneratorEvaluation": { + "methods": [ + "delete_generator_evaluation" + ] + }, + "GetGeneratorEvaluation": { + "methods": [ + "get_generator_evaluation" + ] + }, + "ListGeneratorEvaluations": { + "methods": [ + "list_generator_evaluations" + ] + } + } + }, + "rest": { + "libraryClient": "GeneratorEvaluationsClient", + "rpcs": { + "CreateGeneratorEvaluation": { + "methods": [ + "create_generator_evaluation" + ] + }, + "DeleteGeneratorEvaluation": { + "methods": [ + "delete_generator_evaluation" + ] + }, + "GetGeneratorEvaluation": { + "methods": [ + "get_generator_evaluation" + ] + }, + "ListGeneratorEvaluations": { + "methods": [ + "list_generator_evaluations" + ] + } + } + } + } + }, "Generators": { "clients": { "grpc": { @@ -2012,6 +2091,194 @@ } } }, + "SipTrunks": { + "clients": { + "grpc": { + "libraryClient": "SipTrunksClient", + "rpcs": { + "CreateSipTrunk": { + "methods": [ + "create_sip_trunk" + ] + }, + "DeleteSipTrunk": { + "methods": [ + "delete_sip_trunk" + ] + }, + "GetSipTrunk": { + "methods": [ + "get_sip_trunk" + ] + }, + "ListSipTrunks": { + "methods": [ + "list_sip_trunks" + ] + }, + "UpdateSipTrunk": { + "methods": [ + "update_sip_trunk" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SipTrunksAsyncClient", + "rpcs": { + "CreateSipTrunk": { + "methods": [ + "create_sip_trunk" + ] + }, + "DeleteSipTrunk": { + "methods": [ + "delete_sip_trunk" + ] + }, + "GetSipTrunk": { + "methods": [ + "get_sip_trunk" + ] + }, + "ListSipTrunks": { + "methods": [ + "list_sip_trunks" + ] + }, + "UpdateSipTrunk": { + "methods": [ + "update_sip_trunk" + ] + } + } + }, + "rest": { + "libraryClient": "SipTrunksClient", + "rpcs": { + "CreateSipTrunk": { + "methods": [ + "create_sip_trunk" + ] + }, + "DeleteSipTrunk": { + "methods": [ + "delete_sip_trunk" + ] + }, + "GetSipTrunk": { + "methods": [ + "get_sip_trunk" + ] + }, + "ListSipTrunks": { + "methods": [ + "list_sip_trunks" + ] + }, + "UpdateSipTrunk": { + "methods": [ + "update_sip_trunk" + ] + } + } + } + } + }, + "Tools": { + "clients": { + "grpc": { + "libraryClient": "ToolsClient", + "rpcs": { + "CreateTool": { + "methods": [ + "create_tool" + ] + }, + "DeleteTool": { + "methods": [ + "delete_tool" + ] + }, + "GetTool": { + "methods": [ + "get_tool" + ] + }, + "ListTools": { + "methods": [ + "list_tools" + ] + }, + "UpdateTool": { + "methods": [ + "update_tool" + ] + } + } + }, + "grpc-async": { + "libraryClient": "ToolsAsyncClient", + "rpcs": { + "CreateTool": { + "methods": [ + "create_tool" + ] + }, + "DeleteTool": { + "methods": [ + "delete_tool" + ] + }, + "GetTool": { + "methods": [ + "get_tool" + ] + }, + "ListTools": { + "methods": [ + "list_tools" + ] + }, + "UpdateTool": { + "methods": [ + "update_tool" + ] + } + } + }, + "rest": { + "libraryClient": "ToolsClient", + "rpcs": { + "CreateTool": { + "methods": [ + "create_tool" + ] + }, + "DeleteTool": { + "methods": [ + "delete_tool" + ] + }, + "GetTool": { + "methods": [ + "get_tool" + ] + }, + "ListTools": { + "methods": [ + "list_tools" + ] + }, + "UpdateTool": { + "methods": [ + "update_tool" + ] + } + } + } + } + }, "Versions": { "clients": { "grpc": { diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/answer_records/async_client.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/answer_records/async_client.py index 0a0c9786f5e8..eb10f471fdc4 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/answer_records/async_client.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/answer_records/async_client.py @@ -88,6 +88,8 @@ class AnswerRecordsAsyncClient: parse_context_path = staticmethod(AnswerRecordsClient.parse_context_path) intent_path = staticmethod(AnswerRecordsClient.intent_path) parse_intent_path = staticmethod(AnswerRecordsClient.parse_intent_path) + tool_path = staticmethod(AnswerRecordsClient.tool_path) + parse_tool_path = staticmethod(AnswerRecordsClient.parse_tool_path) common_billing_account_path = staticmethod( AnswerRecordsClient.common_billing_account_path ) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/answer_records/client.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/answer_records/client.py index 796498c8d899..2e3ce7b8c36c 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/answer_records/client.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/answer_records/client.py @@ -287,6 +287,28 @@ def parse_intent_path(path: str) -> Dict[str, str]: m = re.match(r"^projects/(?P.+?)/agent/intents/(?P.+?)$", path) return m.groupdict() if m else {} + @staticmethod + def tool_path( + project: str, + location: str, + tool: str, + ) -> str: + """Returns a fully-qualified tool string.""" + return "projects/{project}/locations/{location}/tools/{tool}".format( + project=project, + location=location, + 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.+?)/tools/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def common_billing_account_path( billing_account: str, diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/conversations/async_client.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/conversations/async_client.py index 566b95683225..bf0056949faf 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/conversations/async_client.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/conversations/async_client.py @@ -119,6 +119,8 @@ class ConversationsAsyncClient: parse_message_path = staticmethod(ConversationsClient.parse_message_path) phrase_set_path = staticmethod(ConversationsClient.phrase_set_path) parse_phrase_set_path = staticmethod(ConversationsClient.parse_phrase_set_path) + tool_path = staticmethod(ConversationsClient.tool_path) + parse_tool_path = staticmethod(ConversationsClient.parse_tool_path) common_billing_account_path = staticmethod( ConversationsClient.common_billing_account_path ) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/conversations/client.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/conversations/client.py index 689a7d2fb19c..adfc2bb7fddf 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/conversations/client.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/conversations/client.py @@ -480,6 +480,28 @@ def parse_phrase_set_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def tool_path( + project: str, + location: str, + tool: str, + ) -> str: + """Returns a fully-qualified tool string.""" + return "projects/{project}/locations/{location}/tools/{tool}".format( + project=project, + location=location, + 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.+?)/tools/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def common_billing_account_path( billing_account: str, diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/generator_evaluations/__init__.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/generator_evaluations/__init__.py new file mode 100644 index 000000000000..a1748a446f71 --- /dev/null +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/generator_evaluations/__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 GeneratorEvaluationsAsyncClient +from .client import GeneratorEvaluationsClient + +__all__ = ( + "GeneratorEvaluationsClient", + "GeneratorEvaluationsAsyncClient", +) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/generator_evaluations/async_client.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/generator_evaluations/async_client.py new file mode 100644 index 000000000000..54c1b8a3c1cb --- /dev/null +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/generator_evaluations/async_client.py @@ -0,0 +1,1098 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +import logging as std_logging +import re +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +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 +import google.protobuf + +from google.cloud.dialogflow_v2 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.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.dialogflow_v2.services.generator_evaluations import pagers +from google.cloud.dialogflow_v2.types import ( + generator_evaluation as gcd_generator_evaluation, +) +from google.cloud.dialogflow_v2.types import generator +from google.cloud.dialogflow_v2.types import generator_evaluation +from google.cloud.dialogflow_v2.types import operations + +from .client import GeneratorEvaluationsClient +from .transports.base import DEFAULT_CLIENT_INFO, GeneratorEvaluationsTransport +from .transports.grpc_asyncio import GeneratorEvaluationsGrpcAsyncIOTransport + +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 GeneratorEvaluationsAsyncClient: + """Service for managing generator evaluations.""" + + _client: GeneratorEvaluationsClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = GeneratorEvaluationsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = GeneratorEvaluationsClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = GeneratorEvaluationsClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = GeneratorEvaluationsClient._DEFAULT_UNIVERSE + + generator_path = staticmethod(GeneratorEvaluationsClient.generator_path) + parse_generator_path = staticmethod(GeneratorEvaluationsClient.parse_generator_path) + generator_evaluation_path = staticmethod( + GeneratorEvaluationsClient.generator_evaluation_path + ) + parse_generator_evaluation_path = staticmethod( + GeneratorEvaluationsClient.parse_generator_evaluation_path + ) + tool_path = staticmethod(GeneratorEvaluationsClient.tool_path) + parse_tool_path = staticmethod(GeneratorEvaluationsClient.parse_tool_path) + common_billing_account_path = staticmethod( + GeneratorEvaluationsClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + GeneratorEvaluationsClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(GeneratorEvaluationsClient.common_folder_path) + parse_common_folder_path = staticmethod( + GeneratorEvaluationsClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + GeneratorEvaluationsClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + GeneratorEvaluationsClient.parse_common_organization_path + ) + common_project_path = staticmethod(GeneratorEvaluationsClient.common_project_path) + parse_common_project_path = staticmethod( + GeneratorEvaluationsClient.parse_common_project_path + ) + common_location_path = staticmethod(GeneratorEvaluationsClient.common_location_path) + parse_common_location_path = staticmethod( + GeneratorEvaluationsClient.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: + GeneratorEvaluationsAsyncClient: The constructed client. + """ + return GeneratorEvaluationsClient.from_service_account_info.__func__(GeneratorEvaluationsAsyncClient, info, *args, **kwargs) # type: ignore + + @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: + GeneratorEvaluationsAsyncClient: The constructed client. + """ + return GeneratorEvaluationsClient.from_service_account_file.__func__(GeneratorEvaluationsAsyncClient, filename, *args, **kwargs) # type: ignore + + 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 GeneratorEvaluationsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> GeneratorEvaluationsTransport: + """Returns the transport used by the client instance. + + Returns: + GeneratorEvaluationsTransport: 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 = GeneratorEvaluationsClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + GeneratorEvaluationsTransport, + Callable[..., GeneratorEvaluationsTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the generator evaluations 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,GeneratorEvaluationsTransport,Callable[..., GeneratorEvaluationsTransport]]]): + 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 GeneratorEvaluationsTransport 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 = GeneratorEvaluationsClient( + 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.dialogflow_v2.GeneratorEvaluationsAsyncClient`.", + extra={ + "serviceName": "google.cloud.dialogflow.v2.GeneratorEvaluations", + "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.dialogflow.v2.GeneratorEvaluations", + "credentialsType": None, + }, + ) + + async def create_generator_evaluation( + self, + request: Optional[ + Union[gcd_generator_evaluation.CreateGeneratorEvaluationRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + generator_evaluation: Optional[ + gcd_generator_evaluation.GeneratorEvaluation + ] = 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 evaluation of a generator. + + .. 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 dialogflow_v2 + + async def sample_create_generator_evaluation(): + # Create a client + client = dialogflow_v2.GeneratorEvaluationsAsyncClient() + + # Initialize request argument(s) + generator_evaluation = dialogflow_v2.GeneratorEvaluation() + generator_evaluation.generator_evaluation_config.input_data_config.input_data_source_type = "INSIGHTS_CONVERSATIONS" + generator_evaluation.generator_evaluation_config.output_gcs_bucket_path = "output_gcs_bucket_path_value" + generator_evaluation.initial_generator.published_model = "published_model_value" + + request = dialogflow_v2.CreateGeneratorEvaluationRequest( + parent="parent_value", + generator_evaluation=generator_evaluation, + ) + + # Make the request + operation = client.create_generator_evaluation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.dialogflow_v2.types.CreateGeneratorEvaluationRequest, dict]]): + The request object. Request of CreateGeneratorEvaluation. + parent (:class:`str`): + Required. The generator resource name. Format: + ``projects//locations//generators/`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + generator_evaluation (:class:`google.cloud.dialogflow_v2.types.GeneratorEvaluation`): + Required. The generator evaluation to + be created. + + This corresponds to the ``generator_evaluation`` 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.dialogflow_v2.types.GeneratorEvaluation` + Represents evaluation result of a generator. + + """ + # 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, generator_evaluation] + 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, gcd_generator_evaluation.CreateGeneratorEvaluationRequest + ): + request = gcd_generator_evaluation.CreateGeneratorEvaluationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if generator_evaluation is not None: + request.generator_evaluation = generator_evaluation + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_generator_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, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gcd_generator_evaluation.GeneratorEvaluation, + metadata_type=operations.GeneratorEvaluationOperationMetadata, + ) + + # Done; return the response. + return response + + async def get_generator_evaluation( + self, + request: Optional[ + Union[generator_evaluation.GetGeneratorEvaluationRequest, 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]]] = (), + ) -> generator_evaluation.GeneratorEvaluation: + r"""Gets an evaluation of generator. + + .. 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 dialogflow_v2 + + async def sample_get_generator_evaluation(): + # Create a client + client = dialogflow_v2.GeneratorEvaluationsAsyncClient() + + # Initialize request argument(s) + request = dialogflow_v2.GetGeneratorEvaluationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_generator_evaluation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.dialogflow_v2.types.GetGeneratorEvaluationRequest, dict]]): + The request object. Request of GetGeneratorEvaluation. + name (:class:`str`): + Required. The generator evaluation resource name. + Format: + ``projects//locations//generators//evaluations/`` + + 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.dialogflow_v2.types.GeneratorEvaluation: + Represents evaluation result of a + generator. + + """ + # 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, generator_evaluation.GetGeneratorEvaluationRequest): + request = generator_evaluation.GetGeneratorEvaluationRequest(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_generator_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 list_generator_evaluations( + self, + request: Optional[ + Union[generator_evaluation.ListGeneratorEvaluationsRequest, 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.ListGeneratorEvaluationsAsyncPager: + r"""Lists evaluations of generator. + + .. 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 dialogflow_v2 + + async def sample_list_generator_evaluations(): + # Create a client + client = dialogflow_v2.GeneratorEvaluationsAsyncClient() + + # Initialize request argument(s) + request = dialogflow_v2.ListGeneratorEvaluationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_generator_evaluations(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.dialogflow_v2.types.ListGeneratorEvaluationsRequest, dict]]): + The request object. Request of ListGeneratorEvaluations. + parent (:class:`str`): + Required. The generator resource name. Format: + ``projects//locations//generators/`` + Wildcard value ``-`` is supported on generator_id to + list evaluations across all generators under same + project. + + 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.dialogflow_v2.services.generator_evaluations.pagers.ListGeneratorEvaluationsAsyncPager: + Response of ListGeneratorEvaluations. + + 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, generator_evaluation.ListGeneratorEvaluationsRequest + ): + request = generator_evaluation.ListGeneratorEvaluationsRequest(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_generator_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.ListGeneratorEvaluationsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_generator_evaluation( + self, + request: Optional[ + Union[generator_evaluation.DeleteGeneratorEvaluationRequest, 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 of generator. + + .. 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 dialogflow_v2 + + async def sample_delete_generator_evaluation(): + # Create a client + client = dialogflow_v2.GeneratorEvaluationsAsyncClient() + + # Initialize request argument(s) + request = dialogflow_v2.DeleteGeneratorEvaluationRequest( + name="name_value", + ) + + # Make the request + await client.delete_generator_evaluation(request=request) + + Args: + request (Optional[Union[google.cloud.dialogflow_v2.types.DeleteGeneratorEvaluationRequest, dict]]): + The request object. Request of DeleteGeneratorEvaluation. + name (:class:`str`): + Required. The generator evaluation resource name. + Format: + ``projects//locations//generators// evaluations/`` + + 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, generator_evaluation.DeleteGeneratorEvaluationRequest + ): + request = generator_evaluation.DeleteGeneratorEvaluationRequest(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_generator_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 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 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) -> "GeneratorEvaluationsAsyncClient": + 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__ = ("GeneratorEvaluationsAsyncClient",) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/generator_evaluations/client.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/generator_evaluations/client.py new file mode 100644 index 000000000000..082573fb966f --- /dev/null +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/generator_evaluations/client.py @@ -0,0 +1,1594 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 http import HTTPStatus +import json +import logging as std_logging +import os +import re +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) +import warnings + +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 +import google.protobuf + +from google.cloud.dialogflow_v2 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.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.dialogflow_v2.services.generator_evaluations import pagers +from google.cloud.dialogflow_v2.types import ( + generator_evaluation as gcd_generator_evaluation, +) +from google.cloud.dialogflow_v2.types import generator +from google.cloud.dialogflow_v2.types import generator_evaluation +from google.cloud.dialogflow_v2.types import operations + +from .transports.base import DEFAULT_CLIENT_INFO, GeneratorEvaluationsTransport +from .transports.grpc import GeneratorEvaluationsGrpcTransport +from .transports.grpc_asyncio import GeneratorEvaluationsGrpcAsyncIOTransport +from .transports.rest import GeneratorEvaluationsRestTransport + + +class GeneratorEvaluationsClientMeta(type): + """Metaclass for the GeneratorEvaluations 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[GeneratorEvaluationsTransport]] + _transport_registry["grpc"] = GeneratorEvaluationsGrpcTransport + _transport_registry["grpc_asyncio"] = GeneratorEvaluationsGrpcAsyncIOTransport + _transport_registry["rest"] = GeneratorEvaluationsRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[GeneratorEvaluationsTransport]: + """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 GeneratorEvaluationsClient(metaclass=GeneratorEvaluationsClientMeta): + """Service for managing generator evaluations.""" + + @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 = "dialogflow.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "dialogflow.{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: + GeneratorEvaluationsClient: 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: + GeneratorEvaluationsClient: 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) -> GeneratorEvaluationsTransport: + """Returns the transport used by the client instance. + + Returns: + GeneratorEvaluationsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def generator_path( + project: str, + location: str, + generator: str, + ) -> str: + """Returns a fully-qualified generator string.""" + return "projects/{project}/locations/{location}/generators/{generator}".format( + project=project, + location=location, + generator=generator, + ) + + @staticmethod + def parse_generator_path(path: str) -> Dict[str, str]: + """Parses a generator path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/generators/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def generator_evaluation_path( + project: str, + location: str, + generator: str, + evaluation: str, + ) -> str: + """Returns a fully-qualified generator_evaluation string.""" + return "projects/{project}/locations/{location}/generators/{generator}/evaluations/{evaluation}".format( + project=project, + location=location, + generator=generator, + evaluation=evaluation, + ) + + @staticmethod + def parse_generator_evaluation_path(path: str) -> Dict[str, str]: + """Parses a generator_evaluation path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/generators/(?P.+?)/evaluations/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def tool_path( + project: str, + location: str, + tool: str, + ) -> str: + """Returns a fully-qualified tool string.""" + return "projects/{project}/locations/{location}/tools/{tool}".format( + project=project, + location=location, + 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.+?)/tools/(?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 = GeneratorEvaluationsClient._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 = GeneratorEvaluationsClient._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 = GeneratorEvaluationsClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = GeneratorEvaluationsClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = GeneratorEvaluationsClient._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 = GeneratorEvaluationsClient._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, + GeneratorEvaluationsTransport, + Callable[..., GeneratorEvaluationsTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the generator evaluations 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,GeneratorEvaluationsTransport,Callable[..., GeneratorEvaluationsTransport]]]): + 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 GeneratorEvaluationsTransport 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, + ) = GeneratorEvaluationsClient._read_environment_variables() + self._client_cert_source = GeneratorEvaluationsClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = GeneratorEvaluationsClient._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, GeneratorEvaluationsTransport) + if transport_provided: + # transport is a GeneratorEvaluationsTransport 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(GeneratorEvaluationsTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or GeneratorEvaluationsClient._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[GeneratorEvaluationsTransport], + Callable[..., GeneratorEvaluationsTransport], + ] = ( + GeneratorEvaluationsClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., GeneratorEvaluationsTransport], 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.dialogflow_v2.GeneratorEvaluationsClient`.", + extra={ + "serviceName": "google.cloud.dialogflow.v2.GeneratorEvaluations", + "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.dialogflow.v2.GeneratorEvaluations", + "credentialsType": None, + }, + ) + + def create_generator_evaluation( + self, + request: Optional[ + Union[gcd_generator_evaluation.CreateGeneratorEvaluationRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + generator_evaluation: Optional[ + gcd_generator_evaluation.GeneratorEvaluation + ] = 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 evaluation of a generator. + + .. 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 dialogflow_v2 + + def sample_create_generator_evaluation(): + # Create a client + client = dialogflow_v2.GeneratorEvaluationsClient() + + # Initialize request argument(s) + generator_evaluation = dialogflow_v2.GeneratorEvaluation() + generator_evaluation.generator_evaluation_config.input_data_config.input_data_source_type = "INSIGHTS_CONVERSATIONS" + generator_evaluation.generator_evaluation_config.output_gcs_bucket_path = "output_gcs_bucket_path_value" + generator_evaluation.initial_generator.published_model = "published_model_value" + + request = dialogflow_v2.CreateGeneratorEvaluationRequest( + parent="parent_value", + generator_evaluation=generator_evaluation, + ) + + # Make the request + operation = client.create_generator_evaluation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.dialogflow_v2.types.CreateGeneratorEvaluationRequest, dict]): + The request object. Request of CreateGeneratorEvaluation. + parent (str): + Required. The generator resource name. Format: + ``projects//locations//generators/`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + generator_evaluation (google.cloud.dialogflow_v2.types.GeneratorEvaluation): + Required. The generator evaluation to + be created. + + This corresponds to the ``generator_evaluation`` 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.dialogflow_v2.types.GeneratorEvaluation` + Represents evaluation result of a generator. + + """ + # 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, generator_evaluation] + 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, gcd_generator_evaluation.CreateGeneratorEvaluationRequest + ): + request = gcd_generator_evaluation.CreateGeneratorEvaluationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if generator_evaluation is not None: + request.generator_evaluation = generator_evaluation + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.create_generator_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, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gcd_generator_evaluation.GeneratorEvaluation, + metadata_type=operations.GeneratorEvaluationOperationMetadata, + ) + + # Done; return the response. + return response + + def get_generator_evaluation( + self, + request: Optional[ + Union[generator_evaluation.GetGeneratorEvaluationRequest, 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]]] = (), + ) -> generator_evaluation.GeneratorEvaluation: + r"""Gets an evaluation of generator. + + .. 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 dialogflow_v2 + + def sample_get_generator_evaluation(): + # Create a client + client = dialogflow_v2.GeneratorEvaluationsClient() + + # Initialize request argument(s) + request = dialogflow_v2.GetGeneratorEvaluationRequest( + name="name_value", + ) + + # Make the request + response = client.get_generator_evaluation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.dialogflow_v2.types.GetGeneratorEvaluationRequest, dict]): + The request object. Request of GetGeneratorEvaluation. + name (str): + Required. The generator evaluation resource name. + Format: + ``projects//locations//generators//evaluations/`` + + 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.dialogflow_v2.types.GeneratorEvaluation: + Represents evaluation result of a + generator. + + """ + # 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, generator_evaluation.GetGeneratorEvaluationRequest): + request = generator_evaluation.GetGeneratorEvaluationRequest(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_generator_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 list_generator_evaluations( + self, + request: Optional[ + Union[generator_evaluation.ListGeneratorEvaluationsRequest, 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.ListGeneratorEvaluationsPager: + r"""Lists evaluations of generator. + + .. 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 dialogflow_v2 + + def sample_list_generator_evaluations(): + # Create a client + client = dialogflow_v2.GeneratorEvaluationsClient() + + # Initialize request argument(s) + request = dialogflow_v2.ListGeneratorEvaluationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_generator_evaluations(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.dialogflow_v2.types.ListGeneratorEvaluationsRequest, dict]): + The request object. Request of ListGeneratorEvaluations. + parent (str): + Required. The generator resource name. Format: + ``projects//locations//generators/`` + Wildcard value ``-`` is supported on generator_id to + list evaluations across all generators under same + project. + + 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.dialogflow_v2.services.generator_evaluations.pagers.ListGeneratorEvaluationsPager: + Response of ListGeneratorEvaluations. + + 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, generator_evaluation.ListGeneratorEvaluationsRequest + ): + request = generator_evaluation.ListGeneratorEvaluationsRequest(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_generator_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.ListGeneratorEvaluationsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_generator_evaluation( + self, + request: Optional[ + Union[generator_evaluation.DeleteGeneratorEvaluationRequest, 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 of generator. + + .. 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 dialogflow_v2 + + def sample_delete_generator_evaluation(): + # Create a client + client = dialogflow_v2.GeneratorEvaluationsClient() + + # Initialize request argument(s) + request = dialogflow_v2.DeleteGeneratorEvaluationRequest( + name="name_value", + ) + + # Make the request + client.delete_generator_evaluation(request=request) + + Args: + request (Union[google.cloud.dialogflow_v2.types.DeleteGeneratorEvaluationRequest, dict]): + The request object. Request of DeleteGeneratorEvaluation. + name (str): + Required. The generator evaluation resource name. + Format: + ``projects//locations//generators// evaluations/`` + + 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, generator_evaluation.DeleteGeneratorEvaluationRequest + ): + request = generator_evaluation.DeleteGeneratorEvaluationRequest(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_generator_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 __enter__(self) -> "GeneratorEvaluationsClient": + 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 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__ = ("GeneratorEvaluationsClient",) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/generator_evaluations/pagers.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/generator_evaluations/pagers.py new file mode 100644 index 000000000000..ffcf521a6ab9 --- /dev/null +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/generator_evaluations/pagers.py @@ -0,0 +1,201 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.dialogflow_v2.types import generator_evaluation + + +class ListGeneratorEvaluationsPager: + """A pager for iterating through ``list_generator_evaluations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.ListGeneratorEvaluationsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``generator_evaluations`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListGeneratorEvaluations`` requests and continue to iterate + through the ``generator_evaluations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.ListGeneratorEvaluationsResponse` + 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[..., generator_evaluation.ListGeneratorEvaluationsResponse], + request: generator_evaluation.ListGeneratorEvaluationsRequest, + response: generator_evaluation.ListGeneratorEvaluationsResponse, + *, + 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.dialogflow_v2.types.ListGeneratorEvaluationsRequest): + The initial request object. + response (google.cloud.dialogflow_v2.types.ListGeneratorEvaluationsResponse): + 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 = generator_evaluation.ListGeneratorEvaluationsRequest(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[generator_evaluation.ListGeneratorEvaluationsResponse]: + 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[generator_evaluation.GeneratorEvaluation]: + for page in self.pages: + yield from page.generator_evaluations + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListGeneratorEvaluationsAsyncPager: + """A pager for iterating through ``list_generator_evaluations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.ListGeneratorEvaluationsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``generator_evaluations`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListGeneratorEvaluations`` requests and continue to iterate + through the ``generator_evaluations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.ListGeneratorEvaluationsResponse` + 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[generator_evaluation.ListGeneratorEvaluationsResponse] + ], + request: generator_evaluation.ListGeneratorEvaluationsRequest, + response: generator_evaluation.ListGeneratorEvaluationsResponse, + *, + 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.dialogflow_v2.types.ListGeneratorEvaluationsRequest): + The initial request object. + response (google.cloud.dialogflow_v2.types.ListGeneratorEvaluationsResponse): + 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 = generator_evaluation.ListGeneratorEvaluationsRequest(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[generator_evaluation.ListGeneratorEvaluationsResponse]: + 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[generator_evaluation.GeneratorEvaluation]: + async def async_generator(): + async for page in self.pages: + for response in page.generator_evaluations: + 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-dialogflow/google/cloud/dialogflow_v2/services/generator_evaluations/transports/README.rst b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/generator_evaluations/transports/README.rst new file mode 100644 index 000000000000..d4d6f1446c83 --- /dev/null +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/generator_evaluations/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`GeneratorEvaluationsTransport` is the ABC for all transports. +- public child `GeneratorEvaluationsGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `GeneratorEvaluationsGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseGeneratorEvaluationsRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `GeneratorEvaluationsRestTransport` 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-dialogflow/google/cloud/dialogflow_v2/services/generator_evaluations/transports/__init__.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/generator_evaluations/transports/__init__.py new file mode 100644 index 000000000000..d8fcc5682d44 --- /dev/null +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/generator_evaluations/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 GeneratorEvaluationsTransport +from .grpc import GeneratorEvaluationsGrpcTransport +from .grpc_asyncio import GeneratorEvaluationsGrpcAsyncIOTransport +from .rest import GeneratorEvaluationsRestInterceptor, GeneratorEvaluationsRestTransport + +# Compile a registry of transports. +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[GeneratorEvaluationsTransport]] +_transport_registry["grpc"] = GeneratorEvaluationsGrpcTransport +_transport_registry["grpc_asyncio"] = GeneratorEvaluationsGrpcAsyncIOTransport +_transport_registry["rest"] = GeneratorEvaluationsRestTransport + +__all__ = ( + "GeneratorEvaluationsTransport", + "GeneratorEvaluationsGrpcTransport", + "GeneratorEvaluationsGrpcAsyncIOTransport", + "GeneratorEvaluationsRestTransport", + "GeneratorEvaluationsRestInterceptor", +) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/generator_evaluations/transports/base.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/generator_evaluations/transports/base.py new file mode 100644 index 000000000000..b8b70957ab1a --- /dev/null +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/generator_evaluations/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 +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 +import google.auth # type: ignore +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 +import google.protobuf +from google.protobuf import empty_pb2 # type: ignore + +from google.cloud.dialogflow_v2 import gapic_version as package_version +from google.cloud.dialogflow_v2.types import ( + generator_evaluation as gcd_generator_evaluation, +) +from google.cloud.dialogflow_v2.types import generator_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 GeneratorEvaluationsTransport(abc.ABC): + """Abstract transport class for GeneratorEvaluations.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ) + + DEFAULT_HOST: str = "dialogflow.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: 'dialogflow.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. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # 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_kwargs, quota_project_id=quota_project_id + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # 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.create_generator_evaluation: gapic_v1.method.wrap_method( + self.create_generator_evaluation, + default_timeout=None, + client_info=client_info, + ), + self.get_generator_evaluation: gapic_v1.method.wrap_method( + self.get_generator_evaluation, + default_timeout=None, + client_info=client_info, + ), + self.list_generator_evaluations: gapic_v1.method.wrap_method( + self.list_generator_evaluations, + default_timeout=None, + client_info=client_info, + ), + self.delete_generator_evaluation: gapic_v1.method.wrap_method( + self.delete_generator_evaluation, + 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.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 create_generator_evaluation( + self, + ) -> Callable[ + [gcd_generator_evaluation.CreateGeneratorEvaluationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_generator_evaluation( + self, + ) -> Callable[ + [generator_evaluation.GetGeneratorEvaluationRequest], + Union[ + generator_evaluation.GeneratorEvaluation, + Awaitable[generator_evaluation.GeneratorEvaluation], + ], + ]: + raise NotImplementedError() + + @property + def list_generator_evaluations( + self, + ) -> Callable[ + [generator_evaluation.ListGeneratorEvaluationsRequest], + Union[ + generator_evaluation.ListGeneratorEvaluationsResponse, + Awaitable[generator_evaluation.ListGeneratorEvaluationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def delete_generator_evaluation( + self, + ) -> Callable[ + [generator_evaluation.DeleteGeneratorEvaluationRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + 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 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__ = ("GeneratorEvaluationsTransport",) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/generator_evaluations/transports/grpc.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/generator_evaluations/transports/grpc.py new file mode 100644 index 000000000000..e6f073951544 --- /dev/null +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/generator_evaluations/transports/grpc.py @@ -0,0 +1,565 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, grpc_helpers, operations_v1 +import google.auth # type: ignore +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 import empty_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore + +from google.cloud.dialogflow_v2.types import ( + generator_evaluation as gcd_generator_evaluation, +) +from google.cloud.dialogflow_v2.types import generator_evaluation + +from .base import DEFAULT_CLIENT_INFO, GeneratorEvaluationsTransport + +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.dialogflow.v2.GeneratorEvaluations", + "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.dialogflow.v2.GeneratorEvaluations", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class GeneratorEvaluationsGrpcTransport(GeneratorEvaluationsTransport): + """gRPC backend transport for GeneratorEvaluations. + + Service for managing generator evaluations. + + 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 = "dialogflow.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: 'dialogflow.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 = "dialogflow.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 create_generator_evaluation( + self, + ) -> Callable[ + [gcd_generator_evaluation.CreateGeneratorEvaluationRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the create generator evaluation method over gRPC. + + Creates evaluation of a generator. + + Returns: + Callable[[~.CreateGeneratorEvaluationRequest], + ~.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_generator_evaluation" not in self._stubs: + self._stubs[ + "create_generator_evaluation" + ] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.v2.GeneratorEvaluations/CreateGeneratorEvaluation", + request_serializer=gcd_generator_evaluation.CreateGeneratorEvaluationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_generator_evaluation"] + + @property + def get_generator_evaluation( + self, + ) -> Callable[ + [generator_evaluation.GetGeneratorEvaluationRequest], + generator_evaluation.GeneratorEvaluation, + ]: + r"""Return a callable for the get generator evaluation method over gRPC. + + Gets an evaluation of generator. + + Returns: + Callable[[~.GetGeneratorEvaluationRequest], + ~.GeneratorEvaluation]: + 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_generator_evaluation" not in self._stubs: + self._stubs["get_generator_evaluation"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.v2.GeneratorEvaluations/GetGeneratorEvaluation", + request_serializer=generator_evaluation.GetGeneratorEvaluationRequest.serialize, + response_deserializer=generator_evaluation.GeneratorEvaluation.deserialize, + ) + return self._stubs["get_generator_evaluation"] + + @property + def list_generator_evaluations( + self, + ) -> Callable[ + [generator_evaluation.ListGeneratorEvaluationsRequest], + generator_evaluation.ListGeneratorEvaluationsResponse, + ]: + r"""Return a callable for the list generator evaluations method over gRPC. + + Lists evaluations of generator. + + Returns: + Callable[[~.ListGeneratorEvaluationsRequest], + ~.ListGeneratorEvaluationsResponse]: + 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_generator_evaluations" not in self._stubs: + self._stubs[ + "list_generator_evaluations" + ] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.v2.GeneratorEvaluations/ListGeneratorEvaluations", + request_serializer=generator_evaluation.ListGeneratorEvaluationsRequest.serialize, + response_deserializer=generator_evaluation.ListGeneratorEvaluationsResponse.deserialize, + ) + return self._stubs["list_generator_evaluations"] + + @property + def delete_generator_evaluation( + self, + ) -> Callable[ + [generator_evaluation.DeleteGeneratorEvaluationRequest], empty_pb2.Empty + ]: + r"""Return a callable for the delete generator evaluation method over gRPC. + + Deletes an evaluation of generator. + + Returns: + Callable[[~.DeleteGeneratorEvaluationRequest], + ~.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_generator_evaluation" not in self._stubs: + self._stubs[ + "delete_generator_evaluation" + ] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.v2.GeneratorEvaluations/DeleteGeneratorEvaluation", + request_serializer=generator_evaluation.DeleteGeneratorEvaluationRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_generator_evaluation"] + + def close(self): + self._logged_channel.close() + + @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__ = ("GeneratorEvaluationsGrpcTransport",) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/generator_evaluations/transports/grpc_asyncio.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/generator_evaluations/transports/grpc_asyncio.py new file mode 100644 index 000000000000..3d5fdc8da491 --- /dev/null +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/generator_evaluations/transports/grpc_asyncio.py @@ -0,0 +1,629 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +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 import empty_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message +import grpc # type: ignore +from grpc.experimental import aio # type: ignore +import proto # type: ignore + +from google.cloud.dialogflow_v2.types import ( + generator_evaluation as gcd_generator_evaluation, +) +from google.cloud.dialogflow_v2.types import generator_evaluation + +from .base import DEFAULT_CLIENT_INFO, GeneratorEvaluationsTransport +from .grpc import GeneratorEvaluationsGrpcTransport + +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.dialogflow.v2.GeneratorEvaluations", + "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.dialogflow.v2.GeneratorEvaluations", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class GeneratorEvaluationsGrpcAsyncIOTransport(GeneratorEvaluationsTransport): + """gRPC AsyncIO backend transport for GeneratorEvaluations. + + Service for managing generator evaluations. + + 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 = "dialogflow.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 = "dialogflow.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: 'dialogflow.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 create_generator_evaluation( + self, + ) -> Callable[ + [gcd_generator_evaluation.CreateGeneratorEvaluationRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the create generator evaluation method over gRPC. + + Creates evaluation of a generator. + + Returns: + Callable[[~.CreateGeneratorEvaluationRequest], + 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_generator_evaluation" not in self._stubs: + self._stubs[ + "create_generator_evaluation" + ] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.v2.GeneratorEvaluations/CreateGeneratorEvaluation", + request_serializer=gcd_generator_evaluation.CreateGeneratorEvaluationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_generator_evaluation"] + + @property + def get_generator_evaluation( + self, + ) -> Callable[ + [generator_evaluation.GetGeneratorEvaluationRequest], + Awaitable[generator_evaluation.GeneratorEvaluation], + ]: + r"""Return a callable for the get generator evaluation method over gRPC. + + Gets an evaluation of generator. + + Returns: + Callable[[~.GetGeneratorEvaluationRequest], + Awaitable[~.GeneratorEvaluation]]: + 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_generator_evaluation" not in self._stubs: + self._stubs["get_generator_evaluation"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.v2.GeneratorEvaluations/GetGeneratorEvaluation", + request_serializer=generator_evaluation.GetGeneratorEvaluationRequest.serialize, + response_deserializer=generator_evaluation.GeneratorEvaluation.deserialize, + ) + return self._stubs["get_generator_evaluation"] + + @property + def list_generator_evaluations( + self, + ) -> Callable[ + [generator_evaluation.ListGeneratorEvaluationsRequest], + Awaitable[generator_evaluation.ListGeneratorEvaluationsResponse], + ]: + r"""Return a callable for the list generator evaluations method over gRPC. + + Lists evaluations of generator. + + Returns: + Callable[[~.ListGeneratorEvaluationsRequest], + Awaitable[~.ListGeneratorEvaluationsResponse]]: + 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_generator_evaluations" not in self._stubs: + self._stubs[ + "list_generator_evaluations" + ] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.v2.GeneratorEvaluations/ListGeneratorEvaluations", + request_serializer=generator_evaluation.ListGeneratorEvaluationsRequest.serialize, + response_deserializer=generator_evaluation.ListGeneratorEvaluationsResponse.deserialize, + ) + return self._stubs["list_generator_evaluations"] + + @property + def delete_generator_evaluation( + self, + ) -> Callable[ + [generator_evaluation.DeleteGeneratorEvaluationRequest], + Awaitable[empty_pb2.Empty], + ]: + r"""Return a callable for the delete generator evaluation method over gRPC. + + Deletes an evaluation of generator. + + Returns: + Callable[[~.DeleteGeneratorEvaluationRequest], + 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_generator_evaluation" not in self._stubs: + self._stubs[ + "delete_generator_evaluation" + ] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.v2.GeneratorEvaluations/DeleteGeneratorEvaluation", + request_serializer=generator_evaluation.DeleteGeneratorEvaluationRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_generator_evaluation"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.create_generator_evaluation: self._wrap_method( + self.create_generator_evaluation, + default_timeout=None, + client_info=client_info, + ), + self.get_generator_evaluation: self._wrap_method( + self.get_generator_evaluation, + default_timeout=None, + client_info=client_info, + ), + self.list_generator_evaluations: self._wrap_method( + self.list_generator_evaluations, + default_timeout=None, + client_info=client_info, + ), + self.delete_generator_evaluation: self._wrap_method( + self.delete_generator_evaluation, + 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.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 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__ = ("GeneratorEvaluationsGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/generator_evaluations/transports/rest.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/generator_evaluations/transports/rest.py new file mode 100644 index 000000000000..50475d493ecc --- /dev/null +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/generator_evaluations/transports/rest.py @@ -0,0 +1,1853 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming +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 # 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 +import google.protobuf +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.dialogflow_v2.types import ( + generator_evaluation as gcd_generator_evaluation, +) +from google.cloud.dialogflow_v2.types import generator_evaluation + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseGeneratorEvaluationsRestTransport + +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 GeneratorEvaluationsRestInterceptor: + """Interceptor for GeneratorEvaluations. + + 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 GeneratorEvaluationsRestTransport. + + .. code-block:: python + class MyCustomGeneratorEvaluationsInterceptor(GeneratorEvaluationsRestInterceptor): + def pre_create_generator_evaluation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_generator_evaluation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_generator_evaluation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_generator_evaluation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_generator_evaluation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_generator_evaluations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_generator_evaluations(self, response): + logging.log(f"Received response: {response}") + return response + + transport = GeneratorEvaluationsRestTransport(interceptor=MyCustomGeneratorEvaluationsInterceptor()) + client = GeneratorEvaluationsClient(transport=transport) + + + """ + + def pre_create_generator_evaluation( + self, + request: gcd_generator_evaluation.CreateGeneratorEvaluationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcd_generator_evaluation.CreateGeneratorEvaluationRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_generator_evaluation + + Override in a subclass to manipulate the request or metadata + before they are sent to the GeneratorEvaluations server. + """ + return request, metadata + + def post_create_generator_evaluation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_generator_evaluation + + DEPRECATED. Please use the `post_create_generator_evaluation_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GeneratorEvaluations server but before + it is returned to user code. This `post_create_generator_evaluation` interceptor runs + before the `post_create_generator_evaluation_with_metadata` interceptor. + """ + return response + + def post_create_generator_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 create_generator_evaluation + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GeneratorEvaluations server but before it is returned to user code. + + We recommend only using this `post_create_generator_evaluation_with_metadata` + interceptor in new development instead of the `post_create_generator_evaluation` interceptor. + When both interceptors are used, this `post_create_generator_evaluation_with_metadata` interceptor runs after the + `post_create_generator_evaluation` interceptor. The (possibly modified) response returned by + `post_create_generator_evaluation` will be passed to + `post_create_generator_evaluation_with_metadata`. + """ + return response, metadata + + def pre_delete_generator_evaluation( + self, + request: generator_evaluation.DeleteGeneratorEvaluationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + generator_evaluation.DeleteGeneratorEvaluationRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_generator_evaluation + + Override in a subclass to manipulate the request or metadata + before they are sent to the GeneratorEvaluations server. + """ + return request, metadata + + def pre_get_generator_evaluation( + self, + request: generator_evaluation.GetGeneratorEvaluationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + generator_evaluation.GetGeneratorEvaluationRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_generator_evaluation + + Override in a subclass to manipulate the request or metadata + before they are sent to the GeneratorEvaluations server. + """ + return request, metadata + + def post_get_generator_evaluation( + self, response: generator_evaluation.GeneratorEvaluation + ) -> generator_evaluation.GeneratorEvaluation: + """Post-rpc interceptor for get_generator_evaluation + + DEPRECATED. Please use the `post_get_generator_evaluation_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GeneratorEvaluations server but before + it is returned to user code. This `post_get_generator_evaluation` interceptor runs + before the `post_get_generator_evaluation_with_metadata` interceptor. + """ + return response + + def post_get_generator_evaluation_with_metadata( + self, + response: generator_evaluation.GeneratorEvaluation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + generator_evaluation.GeneratorEvaluation, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for get_generator_evaluation + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GeneratorEvaluations server but before it is returned to user code. + + We recommend only using this `post_get_generator_evaluation_with_metadata` + interceptor in new development instead of the `post_get_generator_evaluation` interceptor. + When both interceptors are used, this `post_get_generator_evaluation_with_metadata` interceptor runs after the + `post_get_generator_evaluation` interceptor. The (possibly modified) response returned by + `post_get_generator_evaluation` will be passed to + `post_get_generator_evaluation_with_metadata`. + """ + return response, metadata + + def pre_list_generator_evaluations( + self, + request: generator_evaluation.ListGeneratorEvaluationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + generator_evaluation.ListGeneratorEvaluationsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_generator_evaluations + + Override in a subclass to manipulate the request or metadata + before they are sent to the GeneratorEvaluations server. + """ + return request, metadata + + def post_list_generator_evaluations( + self, response: generator_evaluation.ListGeneratorEvaluationsResponse + ) -> generator_evaluation.ListGeneratorEvaluationsResponse: + """Post-rpc interceptor for list_generator_evaluations + + DEPRECATED. Please use the `post_list_generator_evaluations_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the GeneratorEvaluations server but before + it is returned to user code. This `post_list_generator_evaluations` interceptor runs + before the `post_list_generator_evaluations_with_metadata` interceptor. + """ + return response + + def post_list_generator_evaluations_with_metadata( + self, + response: generator_evaluation.ListGeneratorEvaluationsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + generator_evaluation.ListGeneratorEvaluationsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_generator_evaluations + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the GeneratorEvaluations server but before it is returned to user code. + + We recommend only using this `post_list_generator_evaluations_with_metadata` + interceptor in new development instead of the `post_list_generator_evaluations` interceptor. + When both interceptors are used, this `post_list_generator_evaluations_with_metadata` interceptor runs after the + `post_list_generator_evaluations` interceptor. The (possibly modified) response returned by + `post_list_generator_evaluations` will be passed to + `post_list_generator_evaluations_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 GeneratorEvaluations 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 GeneratorEvaluations 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 GeneratorEvaluations 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 GeneratorEvaluations 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 GeneratorEvaluations 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 GeneratorEvaluations 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 GeneratorEvaluations 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 GeneratorEvaluations 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 GeneratorEvaluations 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 GeneratorEvaluations server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class GeneratorEvaluationsRestStub: + _session: AuthorizedSession + _host: str + _interceptor: GeneratorEvaluationsRestInterceptor + + +class GeneratorEvaluationsRestTransport(_BaseGeneratorEvaluationsRestTransport): + """REST backend synchronous transport for GeneratorEvaluations. + + Service for managing generator evaluations. + + 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 = "dialogflow.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[GeneratorEvaluationsRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'dialogflow.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 GeneratorEvaluationsRestInterceptor() + 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": "/v2/{name=projects/*/operations/*}:cancel", + }, + { + "method": "post", + "uri": "/v2/{name=projects/*/locations/*/operations/*}:cancel", + }, + ], + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v2/{name=projects/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v2/{name=projects/*}/operations", + }, + { + "method": "get", + "uri": "/v2/{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="v2", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _CreateGeneratorEvaluation( + _BaseGeneratorEvaluationsRestTransport._BaseCreateGeneratorEvaluation, + GeneratorEvaluationsRestStub, + ): + def __hash__(self): + return hash("GeneratorEvaluationsRestTransport.CreateGeneratorEvaluation") + + @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: gcd_generator_evaluation.CreateGeneratorEvaluationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create generator + evaluation method over HTTP. + + Args: + request (~.gcd_generator_evaluation.CreateGeneratorEvaluationRequest): + The request object. Request of CreateGeneratorEvaluation. + 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 = ( + _BaseGeneratorEvaluationsRestTransport._BaseCreateGeneratorEvaluation._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_generator_evaluation( + request, metadata + ) + transcoded_request = _BaseGeneratorEvaluationsRestTransport._BaseCreateGeneratorEvaluation._get_transcoded_request( + http_options, request + ) + + body = _BaseGeneratorEvaluationsRestTransport._BaseCreateGeneratorEvaluation._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseGeneratorEvaluationsRestTransport._BaseCreateGeneratorEvaluation._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.dialogflow_v2.GeneratorEvaluationsClient.CreateGeneratorEvaluation", + extra={ + "serviceName": "google.cloud.dialogflow.v2.GeneratorEvaluations", + "rpcName": "CreateGeneratorEvaluation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GeneratorEvaluationsRestTransport._CreateGeneratorEvaluation._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_generator_evaluation(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_generator_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.dialogflow_v2.GeneratorEvaluationsClient.create_generator_evaluation", + extra={ + "serviceName": "google.cloud.dialogflow.v2.GeneratorEvaluations", + "rpcName": "CreateGeneratorEvaluation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteGeneratorEvaluation( + _BaseGeneratorEvaluationsRestTransport._BaseDeleteGeneratorEvaluation, + GeneratorEvaluationsRestStub, + ): + def __hash__(self): + return hash("GeneratorEvaluationsRestTransport.DeleteGeneratorEvaluation") + + @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: generator_evaluation.DeleteGeneratorEvaluationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete generator + evaluation method over HTTP. + + Args: + request (~.generator_evaluation.DeleteGeneratorEvaluationRequest): + The request object. Request of DeleteGeneratorEvaluation. + 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 = ( + _BaseGeneratorEvaluationsRestTransport._BaseDeleteGeneratorEvaluation._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_generator_evaluation( + request, metadata + ) + transcoded_request = _BaseGeneratorEvaluationsRestTransport._BaseDeleteGeneratorEvaluation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseGeneratorEvaluationsRestTransport._BaseDeleteGeneratorEvaluation._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.dialogflow_v2.GeneratorEvaluationsClient.DeleteGeneratorEvaluation", + extra={ + "serviceName": "google.cloud.dialogflow.v2.GeneratorEvaluations", + "rpcName": "DeleteGeneratorEvaluation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GeneratorEvaluationsRestTransport._DeleteGeneratorEvaluation._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 _GetGeneratorEvaluation( + _BaseGeneratorEvaluationsRestTransport._BaseGetGeneratorEvaluation, + GeneratorEvaluationsRestStub, + ): + def __hash__(self): + return hash("GeneratorEvaluationsRestTransport.GetGeneratorEvaluation") + + @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: generator_evaluation.GetGeneratorEvaluationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> generator_evaluation.GeneratorEvaluation: + r"""Call the get generator evaluation method over HTTP. + + Args: + request (~.generator_evaluation.GetGeneratorEvaluationRequest): + The request object. Request of GetGeneratorEvaluation. + 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: + ~.generator_evaluation.GeneratorEvaluation: + Represents evaluation result of a + generator. + + """ + + http_options = ( + _BaseGeneratorEvaluationsRestTransport._BaseGetGeneratorEvaluation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_generator_evaluation( + request, metadata + ) + transcoded_request = _BaseGeneratorEvaluationsRestTransport._BaseGetGeneratorEvaluation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseGeneratorEvaluationsRestTransport._BaseGetGeneratorEvaluation._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.dialogflow_v2.GeneratorEvaluationsClient.GetGeneratorEvaluation", + extra={ + "serviceName": "google.cloud.dialogflow.v2.GeneratorEvaluations", + "rpcName": "GetGeneratorEvaluation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + GeneratorEvaluationsRestTransport._GetGeneratorEvaluation._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 = generator_evaluation.GeneratorEvaluation() + pb_resp = generator_evaluation.GeneratorEvaluation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_generator_evaluation(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_generator_evaluation_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = generator_evaluation.GeneratorEvaluation.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.dialogflow_v2.GeneratorEvaluationsClient.get_generator_evaluation", + extra={ + "serviceName": "google.cloud.dialogflow.v2.GeneratorEvaluations", + "rpcName": "GetGeneratorEvaluation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListGeneratorEvaluations( + _BaseGeneratorEvaluationsRestTransport._BaseListGeneratorEvaluations, + GeneratorEvaluationsRestStub, + ): + def __hash__(self): + return hash("GeneratorEvaluationsRestTransport.ListGeneratorEvaluations") + + @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: generator_evaluation.ListGeneratorEvaluationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> generator_evaluation.ListGeneratorEvaluationsResponse: + r"""Call the list generator + evaluations method over HTTP. + + Args: + request (~.generator_evaluation.ListGeneratorEvaluationsRequest): + The request object. Request of ListGeneratorEvaluations. + 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: + ~.generator_evaluation.ListGeneratorEvaluationsResponse: + Response of ListGeneratorEvaluations. + """ + + http_options = ( + _BaseGeneratorEvaluationsRestTransport._BaseListGeneratorEvaluations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_generator_evaluations( + request, metadata + ) + transcoded_request = _BaseGeneratorEvaluationsRestTransport._BaseListGeneratorEvaluations._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseGeneratorEvaluationsRestTransport._BaseListGeneratorEvaluations._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.dialogflow_v2.GeneratorEvaluationsClient.ListGeneratorEvaluations", + extra={ + "serviceName": "google.cloud.dialogflow.v2.GeneratorEvaluations", + "rpcName": "ListGeneratorEvaluations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GeneratorEvaluationsRestTransport._ListGeneratorEvaluations._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 = generator_evaluation.ListGeneratorEvaluationsResponse() + pb_resp = generator_evaluation.ListGeneratorEvaluationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_generator_evaluations(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_generator_evaluations_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + generator_evaluation.ListGeneratorEvaluationsResponse.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.dialogflow_v2.GeneratorEvaluationsClient.list_generator_evaluations", + extra={ + "serviceName": "google.cloud.dialogflow.v2.GeneratorEvaluations", + "rpcName": "ListGeneratorEvaluations", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_generator_evaluation( + self, + ) -> Callable[ + [gcd_generator_evaluation.CreateGeneratorEvaluationRequest], + 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._CreateGeneratorEvaluation(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_generator_evaluation( + self, + ) -> Callable[ + [generator_evaluation.DeleteGeneratorEvaluationRequest], 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._DeleteGeneratorEvaluation(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_generator_evaluation( + self, + ) -> Callable[ + [generator_evaluation.GetGeneratorEvaluationRequest], + generator_evaluation.GeneratorEvaluation, + ]: + # 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._GetGeneratorEvaluation(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_generator_evaluations( + self, + ) -> Callable[ + [generator_evaluation.ListGeneratorEvaluationsRequest], + generator_evaluation.ListGeneratorEvaluationsResponse, + ]: + # 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._ListGeneratorEvaluations(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( + _BaseGeneratorEvaluationsRestTransport._BaseGetLocation, + GeneratorEvaluationsRestStub, + ): + def __hash__(self): + return hash("GeneratorEvaluationsRestTransport.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 = ( + _BaseGeneratorEvaluationsRestTransport._BaseGetLocation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_location(request, metadata) + transcoded_request = _BaseGeneratorEvaluationsRestTransport._BaseGetLocation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseGeneratorEvaluationsRestTransport._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.dialogflow_v2.GeneratorEvaluationsClient.GetLocation", + extra={ + "serviceName": "google.cloud.dialogflow.v2.GeneratorEvaluations", + "rpcName": "GetLocation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GeneratorEvaluationsRestTransport._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.dialogflow_v2.GeneratorEvaluationsAsyncClient.GetLocation", + extra={ + "serviceName": "google.cloud.dialogflow.v2.GeneratorEvaluations", + "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( + _BaseGeneratorEvaluationsRestTransport._BaseListLocations, + GeneratorEvaluationsRestStub, + ): + def __hash__(self): + return hash("GeneratorEvaluationsRestTransport.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 = ( + _BaseGeneratorEvaluationsRestTransport._BaseListLocations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + transcoded_request = _BaseGeneratorEvaluationsRestTransport._BaseListLocations._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseGeneratorEvaluationsRestTransport._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.dialogflow_v2.GeneratorEvaluationsClient.ListLocations", + extra={ + "serviceName": "google.cloud.dialogflow.v2.GeneratorEvaluations", + "rpcName": "ListLocations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GeneratorEvaluationsRestTransport._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.dialogflow_v2.GeneratorEvaluationsAsyncClient.ListLocations", + extra={ + "serviceName": "google.cloud.dialogflow.v2.GeneratorEvaluations", + "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( + _BaseGeneratorEvaluationsRestTransport._BaseCancelOperation, + GeneratorEvaluationsRestStub, + ): + def __hash__(self): + return hash("GeneratorEvaluationsRestTransport.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), + ) + 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 = ( + _BaseGeneratorEvaluationsRestTransport._BaseCancelOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + transcoded_request = _BaseGeneratorEvaluationsRestTransport._BaseCancelOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseGeneratorEvaluationsRestTransport._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.dialogflow_v2.GeneratorEvaluationsClient.CancelOperation", + extra={ + "serviceName": "google.cloud.dialogflow.v2.GeneratorEvaluations", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GeneratorEvaluationsRestTransport._CancelOperation._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_cancel_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation( + _BaseGeneratorEvaluationsRestTransport._BaseGetOperation, + GeneratorEvaluationsRestStub, + ): + def __hash__(self): + return hash("GeneratorEvaluationsRestTransport.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 = ( + _BaseGeneratorEvaluationsRestTransport._BaseGetOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseGeneratorEvaluationsRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseGeneratorEvaluationsRestTransport._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.dialogflow_v2.GeneratorEvaluationsClient.GetOperation", + extra={ + "serviceName": "google.cloud.dialogflow.v2.GeneratorEvaluations", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GeneratorEvaluationsRestTransport._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.dialogflow_v2.GeneratorEvaluationsAsyncClient.GetOperation", + extra={ + "serviceName": "google.cloud.dialogflow.v2.GeneratorEvaluations", + "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( + _BaseGeneratorEvaluationsRestTransport._BaseListOperations, + GeneratorEvaluationsRestStub, + ): + def __hash__(self): + return hash("GeneratorEvaluationsRestTransport.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 = ( + _BaseGeneratorEvaluationsRestTransport._BaseListOperations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = _BaseGeneratorEvaluationsRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseGeneratorEvaluationsRestTransport._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.dialogflow_v2.GeneratorEvaluationsClient.ListOperations", + extra={ + "serviceName": "google.cloud.dialogflow.v2.GeneratorEvaluations", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = GeneratorEvaluationsRestTransport._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.dialogflow_v2.GeneratorEvaluationsAsyncClient.ListOperations", + extra={ + "serviceName": "google.cloud.dialogflow.v2.GeneratorEvaluations", + "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__ = ("GeneratorEvaluationsRestTransport",) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/generator_evaluations/transports/rest_base.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/generator_evaluations/transports/rest_base.py new file mode 100644 index 000000000000..b95d0681cc32 --- /dev/null +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/generator_evaluations/transports/rest_base.py @@ -0,0 +1,438 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 empty_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.dialogflow_v2.types import ( + generator_evaluation as gcd_generator_evaluation, +) +from google.cloud.dialogflow_v2.types import generator_evaluation + +from .base import DEFAULT_CLIENT_INFO, GeneratorEvaluationsTransport + + +class _BaseGeneratorEvaluationsRestTransport(GeneratorEvaluationsTransport): + """Base REST backend transport for GeneratorEvaluations. + + 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 = "dialogflow.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: 'dialogflow.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 _BaseCreateGeneratorEvaluation: + 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": "/v2/{parent=projects/*/locations/*/generators/*}/evaluations", + "body": "generator_evaluation", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcd_generator_evaluation.CreateGeneratorEvaluationRequest.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( + _BaseGeneratorEvaluationsRestTransport._BaseCreateGeneratorEvaluation._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteGeneratorEvaluation: + 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": "/v2/{name=projects/*/locations/*/generators/*/evaluations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = generator_evaluation.DeleteGeneratorEvaluationRequest.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( + _BaseGeneratorEvaluationsRestTransport._BaseDeleteGeneratorEvaluation._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetGeneratorEvaluation: + 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": "/v2/{name=projects/*/locations/*/generators/*/evaluations/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = generator_evaluation.GetGeneratorEvaluationRequest.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( + _BaseGeneratorEvaluationsRestTransport._BaseGetGeneratorEvaluation._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListGeneratorEvaluations: + 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": "/v2/{parent=projects/*/locations/*/generators/*}/evaluations", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = generator_evaluation.ListGeneratorEvaluationsRequest.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( + _BaseGeneratorEvaluationsRestTransport._BaseListGeneratorEvaluations._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": "/v2/{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": "/v2/{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": "/v2/{name=projects/*/operations/*}:cancel", + }, + { + "method": "post", + "uri": "/v2/{name=projects/*/locations/*/operations/*}:cancel", + }, + ] + 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": "/v2/{name=projects/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2/{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": "/v2/{name=projects/*}/operations", + }, + { + "method": "get", + "uri": "/v2/{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__ = ("_BaseGeneratorEvaluationsRestTransport",) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/generators/async_client.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/generators/async_client.py index 0fc0c160a868..121fc6b49847 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/generators/async_client.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/generators/async_client.py @@ -86,6 +86,8 @@ class GeneratorsAsyncClient: generator_path = staticmethod(GeneratorsClient.generator_path) parse_generator_path = staticmethod(GeneratorsClient.parse_generator_path) + tool_path = staticmethod(GeneratorsClient.tool_path) + parse_tool_path = staticmethod(GeneratorsClient.parse_tool_path) common_billing_account_path = staticmethod( GeneratorsClient.common_billing_account_path ) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/generators/client.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/generators/client.py index b4db763056f8..c7b098fe1b2d 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/generators/client.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/generators/client.py @@ -255,6 +255,28 @@ def parse_generator_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def tool_path( + project: str, + location: str, + tool: str, + ) -> str: + """Returns a fully-qualified tool string.""" + return "projects/{project}/locations/{location}/tools/{tool}".format( + project=project, + location=location, + 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.+?)/tools/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def common_billing_account_path( billing_account: str, diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/participants/async_client.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/participants/async_client.py index 7e0d5466276f..9a52ab5dab9e 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/participants/async_client.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/participants/async_client.py @@ -100,6 +100,8 @@ class ParticipantsAsyncClient: parse_session_entity_type_path = staticmethod( ParticipantsClient.parse_session_entity_type_path ) + tool_path = staticmethod(ParticipantsClient.tool_path) + parse_tool_path = staticmethod(ParticipantsClient.parse_tool_path) common_billing_account_path = staticmethod( ParticipantsClient.common_billing_account_path ) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/participants/client.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/participants/client.py index 733a93d35ece..a6d5f4c00f19 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/participants/client.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/participants/client.py @@ -380,6 +380,28 @@ def parse_session_entity_type_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def tool_path( + project: str, + location: str, + tool: str, + ) -> str: + """Returns a fully-qualified tool string.""" + return "projects/{project}/locations/{location}/tools/{tool}".format( + project=project, + location=location, + 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.+?)/tools/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def common_billing_account_path( billing_account: str, diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/sip_trunks/__init__.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/sip_trunks/__init__.py new file mode 100644 index 000000000000..1ff9dce33b02 --- /dev/null +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/sip_trunks/__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 SipTrunksAsyncClient +from .client import SipTrunksClient + +__all__ = ( + "SipTrunksClient", + "SipTrunksAsyncClient", +) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/sip_trunks/async_client.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/sip_trunks/async_client.py new file mode 100644 index 000000000000..a8f58bcc0a09 --- /dev/null +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/sip_trunks/async_client.py @@ -0,0 +1,1173 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +import logging as std_logging +import re +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +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 +import google.protobuf + +from google.cloud.dialogflow_v2 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.protobuf import field_mask_pb2 # type: ignore + +from google.cloud.dialogflow_v2.services.sip_trunks import pagers +from google.cloud.dialogflow_v2.types import sip_trunk +from google.cloud.dialogflow_v2.types import sip_trunk as gcd_sip_trunk + +from .client import SipTrunksClient +from .transports.base import DEFAULT_CLIENT_INFO, SipTrunksTransport +from .transports.grpc_asyncio import SipTrunksGrpcAsyncIOTransport + +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 SipTrunksAsyncClient: + """Service for managing + [SipTrunks][google.cloud.dialogflow.v2.SipTrunk]. + """ + + _client: SipTrunksClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = SipTrunksClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SipTrunksClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = SipTrunksClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = SipTrunksClient._DEFAULT_UNIVERSE + + sip_trunk_path = staticmethod(SipTrunksClient.sip_trunk_path) + parse_sip_trunk_path = staticmethod(SipTrunksClient.parse_sip_trunk_path) + common_billing_account_path = staticmethod( + SipTrunksClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + SipTrunksClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(SipTrunksClient.common_folder_path) + parse_common_folder_path = staticmethod(SipTrunksClient.parse_common_folder_path) + common_organization_path = staticmethod(SipTrunksClient.common_organization_path) + parse_common_organization_path = staticmethod( + SipTrunksClient.parse_common_organization_path + ) + common_project_path = staticmethod(SipTrunksClient.common_project_path) + parse_common_project_path = staticmethod(SipTrunksClient.parse_common_project_path) + common_location_path = staticmethod(SipTrunksClient.common_location_path) + parse_common_location_path = staticmethod( + SipTrunksClient.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: + SipTrunksAsyncClient: The constructed client. + """ + return SipTrunksClient.from_service_account_info.__func__(SipTrunksAsyncClient, info, *args, **kwargs) # type: ignore + + @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: + SipTrunksAsyncClient: The constructed client. + """ + return SipTrunksClient.from_service_account_file.__func__(SipTrunksAsyncClient, filename, *args, **kwargs) # type: ignore + + 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 SipTrunksClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> SipTrunksTransport: + """Returns the transport used by the client instance. + + Returns: + SipTrunksTransport: 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 = SipTrunksClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, SipTrunksTransport, Callable[..., SipTrunksTransport]] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the sip trunks 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,SipTrunksTransport,Callable[..., SipTrunksTransport]]]): + 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 SipTrunksTransport 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 = SipTrunksClient( + 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.dialogflow_v2.SipTrunksAsyncClient`.", + extra={ + "serviceName": "google.cloud.dialogflow.v2.SipTrunks", + "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.dialogflow.v2.SipTrunks", + "credentialsType": None, + }, + ) + + async def create_sip_trunk( + self, + request: Optional[Union[gcd_sip_trunk.CreateSipTrunkRequest, dict]] = None, + *, + parent: Optional[str] = None, + sip_trunk: Optional[gcd_sip_trunk.SipTrunk] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcd_sip_trunk.SipTrunk: + r"""Creates a SipTrunk for a specified 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 dialogflow_v2 + + async def sample_create_sip_trunk(): + # Create a client + client = dialogflow_v2.SipTrunksAsyncClient() + + # Initialize request argument(s) + sip_trunk = dialogflow_v2.SipTrunk() + sip_trunk.expected_hostname = ['expected_hostname_value1', 'expected_hostname_value2'] + + request = dialogflow_v2.CreateSipTrunkRequest( + parent="parent_value", + sip_trunk=sip_trunk, + ) + + # Make the request + response = await client.create_sip_trunk(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.dialogflow_v2.types.CreateSipTrunkRequest, dict]]): + The request object. The request message for + [SipTrunks.CreateSipTrunk][google.cloud.dialogflow.v2.SipTrunks.CreateSipTrunk]. + parent (:class:`str`): + Required. The location to create a SIP trunk for. + Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + sip_trunk (:class:`google.cloud.dialogflow_v2.types.SipTrunk`): + Required. The SIP trunk to create. + This corresponds to the ``sip_trunk`` 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.dialogflow_v2.types.SipTrunk: + SipTrunk is the resource that + represents a SIP trunk to connect to + Google Telephony platform SIP trunking + service. + + """ + # 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, sip_trunk] + 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, gcd_sip_trunk.CreateSipTrunkRequest): + request = gcd_sip_trunk.CreateSipTrunkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if sip_trunk is not None: + request.sip_trunk = sip_trunk + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_sip_trunk + ] + + # 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_sip_trunk( + self, + request: Optional[Union[sip_trunk.DeleteSipTrunkRequest, 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 specified SipTrunk. + + .. 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 dialogflow_v2 + + async def sample_delete_sip_trunk(): + # Create a client + client = dialogflow_v2.SipTrunksAsyncClient() + + # Initialize request argument(s) + request = dialogflow_v2.DeleteSipTrunkRequest( + name="name_value", + ) + + # Make the request + await client.delete_sip_trunk(request=request) + + Args: + request (Optional[Union[google.cloud.dialogflow_v2.types.DeleteSipTrunkRequest, dict]]): + The request object. The request message for + [SipTrunks.DeleteSipTrunk][google.cloud.dialogflow.v2.SipTrunks.DeleteSipTrunk]. + name (:class:`str`): + Required. The name of the SIP trunk to delete. Format: + ``projects//locations//sipTrunks/``. + + 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, sip_trunk.DeleteSipTrunkRequest): + request = sip_trunk.DeleteSipTrunkRequest(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_sip_trunk + ] + + # 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_sip_trunks( + self, + request: Optional[Union[sip_trunk.ListSipTrunksRequest, 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.ListSipTrunksAsyncPager: + r"""Returns a list of SipTrunks in the specified + 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 dialogflow_v2 + + async def sample_list_sip_trunks(): + # Create a client + client = dialogflow_v2.SipTrunksAsyncClient() + + # Initialize request argument(s) + request = dialogflow_v2.ListSipTrunksRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sip_trunks(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.dialogflow_v2.types.ListSipTrunksRequest, dict]]): + The request object. The request message for + [SipTrunks.ListSipTrunks][google.cloud.dialogflow.v2.SipTrunks.ListSipTrunks]. + parent (:class:`str`): + Required. The location to list SIP trunks from. Format: + ``projects//locations/``. + + 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.dialogflow_v2.services.sip_trunks.pagers.ListSipTrunksAsyncPager: + The response message for + [SipTrunks.ListSipTrunks][google.cloud.dialogflow.v2.SipTrunks.ListSipTrunks]. + + 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, sip_trunk.ListSipTrunksRequest): + request = sip_trunk.ListSipTrunksRequest(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_sip_trunks + ] + + # 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.ListSipTrunksAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_sip_trunk( + self, + request: Optional[Union[sip_trunk.GetSipTrunkRequest, 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]]] = (), + ) -> sip_trunk.SipTrunk: + r"""Retrieves the specified SipTrunk. + + .. 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 dialogflow_v2 + + async def sample_get_sip_trunk(): + # Create a client + client = dialogflow_v2.SipTrunksAsyncClient() + + # Initialize request argument(s) + request = dialogflow_v2.GetSipTrunkRequest( + name="name_value", + ) + + # Make the request + response = await client.get_sip_trunk(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.dialogflow_v2.types.GetSipTrunkRequest, dict]]): + The request object. The request message for + [SipTrunks.GetSipTrunk][google.cloud.dialogflow.v2.SipTrunks.GetSipTrunk]. + name (:class:`str`): + Required. The name of the SIP trunk to delete. Format: + ``projects//locations//sipTrunks/``. + + 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.dialogflow_v2.types.SipTrunk: + SipTrunk is the resource that + represents a SIP trunk to connect to + Google Telephony platform SIP trunking + service. + + """ + # 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, sip_trunk.GetSipTrunkRequest): + request = sip_trunk.GetSipTrunkRequest(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_sip_trunk + ] + + # 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 update_sip_trunk( + self, + request: Optional[Union[gcd_sip_trunk.UpdateSipTrunkRequest, dict]] = None, + *, + sip_trunk: Optional[gcd_sip_trunk.SipTrunk] = 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]]] = (), + ) -> gcd_sip_trunk.SipTrunk: + r"""Updates the specified SipTrunk. + + .. 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 dialogflow_v2 + + async def sample_update_sip_trunk(): + # Create a client + client = dialogflow_v2.SipTrunksAsyncClient() + + # Initialize request argument(s) + sip_trunk = dialogflow_v2.SipTrunk() + sip_trunk.expected_hostname = ['expected_hostname_value1', 'expected_hostname_value2'] + + request = dialogflow_v2.UpdateSipTrunkRequest( + sip_trunk=sip_trunk, + ) + + # Make the request + response = await client.update_sip_trunk(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.dialogflow_v2.types.UpdateSipTrunkRequest, dict]]): + The request object. The request message for + [SipTrunks.UpdateSipTrunk][google.cloud.dialogflow.v2.SipTrunks.UpdateSipTrunk]. + sip_trunk (:class:`google.cloud.dialogflow_v2.types.SipTrunk`): + Required. The SipTrunk to update. + This corresponds to the ``sip_trunk`` 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 mask 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.dialogflow_v2.types.SipTrunk: + SipTrunk is the resource that + represents a SIP trunk to connect to + Google Telephony platform SIP trunking + service. + + """ + # 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 = [sip_trunk, 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, gcd_sip_trunk.UpdateSipTrunkRequest): + request = gcd_sip_trunk.UpdateSipTrunkRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if sip_trunk is not None: + request.sip_trunk = sip_trunk + 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_sip_trunk + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("sip_trunk.name", request.sip_trunk.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 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) -> "SipTrunksAsyncClient": + 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__ = ("SipTrunksAsyncClient",) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/sip_trunks/client.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/sip_trunks/client.py new file mode 100644 index 000000000000..5fd6ba75313d --- /dev/null +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/sip_trunks/client.py @@ -0,0 +1,1622 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 http import HTTPStatus +import json +import logging as std_logging +import os +import re +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) +import warnings + +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 +import google.protobuf + +from google.cloud.dialogflow_v2 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.protobuf import field_mask_pb2 # type: ignore + +from google.cloud.dialogflow_v2.services.sip_trunks import pagers +from google.cloud.dialogflow_v2.types import sip_trunk +from google.cloud.dialogflow_v2.types import sip_trunk as gcd_sip_trunk + +from .transports.base import DEFAULT_CLIENT_INFO, SipTrunksTransport +from .transports.grpc import SipTrunksGrpcTransport +from .transports.grpc_asyncio import SipTrunksGrpcAsyncIOTransport +from .transports.rest import SipTrunksRestTransport + + +class SipTrunksClientMeta(type): + """Metaclass for the SipTrunks 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[SipTrunksTransport]] + _transport_registry["grpc"] = SipTrunksGrpcTransport + _transport_registry["grpc_asyncio"] = SipTrunksGrpcAsyncIOTransport + _transport_registry["rest"] = SipTrunksRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[SipTrunksTransport]: + """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 SipTrunksClient(metaclass=SipTrunksClientMeta): + """Service for managing + [SipTrunks][google.cloud.dialogflow.v2.SipTrunk]. + """ + + @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 = "dialogflow.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "dialogflow.{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: + SipTrunksClient: 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: + SipTrunksClient: 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) -> SipTrunksTransport: + """Returns the transport used by the client instance. + + Returns: + SipTrunksTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def sip_trunk_path( + project: str, + location: str, + siptrunk: str, + ) -> str: + """Returns a fully-qualified sip_trunk string.""" + return "projects/{project}/locations/{location}/sipTrunks/{siptrunk}".format( + project=project, + location=location, + siptrunk=siptrunk, + ) + + @staticmethod + def parse_sip_trunk_path(path: str) -> Dict[str, str]: + """Parses a sip_trunk path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/sipTrunks/(?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 = SipTrunksClient._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 = SipTrunksClient._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 = SipTrunksClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = SipTrunksClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = SipTrunksClient._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 = SipTrunksClient._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, SipTrunksTransport, Callable[..., SipTrunksTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the sip trunks 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,SipTrunksTransport,Callable[..., SipTrunksTransport]]]): + 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 SipTrunksTransport 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, + ) = SipTrunksClient._read_environment_variables() + self._client_cert_source = SipTrunksClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = SipTrunksClient._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, SipTrunksTransport) + if transport_provided: + # transport is a SipTrunksTransport 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(SipTrunksTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = self._api_endpoint or SipTrunksClient._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[SipTrunksTransport], Callable[..., SipTrunksTransport] + ] = ( + SipTrunksClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., SipTrunksTransport], 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.dialogflow_v2.SipTrunksClient`.", + extra={ + "serviceName": "google.cloud.dialogflow.v2.SipTrunks", + "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.dialogflow.v2.SipTrunks", + "credentialsType": None, + }, + ) + + def create_sip_trunk( + self, + request: Optional[Union[gcd_sip_trunk.CreateSipTrunkRequest, dict]] = None, + *, + parent: Optional[str] = None, + sip_trunk: Optional[gcd_sip_trunk.SipTrunk] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcd_sip_trunk.SipTrunk: + r"""Creates a SipTrunk for a specified 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 dialogflow_v2 + + def sample_create_sip_trunk(): + # Create a client + client = dialogflow_v2.SipTrunksClient() + + # Initialize request argument(s) + sip_trunk = dialogflow_v2.SipTrunk() + sip_trunk.expected_hostname = ['expected_hostname_value1', 'expected_hostname_value2'] + + request = dialogflow_v2.CreateSipTrunkRequest( + parent="parent_value", + sip_trunk=sip_trunk, + ) + + # Make the request + response = client.create_sip_trunk(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.dialogflow_v2.types.CreateSipTrunkRequest, dict]): + The request object. The request message for + [SipTrunks.CreateSipTrunk][google.cloud.dialogflow.v2.SipTrunks.CreateSipTrunk]. + parent (str): + Required. The location to create a SIP trunk for. + Format: + ``projects//locations/``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + sip_trunk (google.cloud.dialogflow_v2.types.SipTrunk): + Required. The SIP trunk to create. + This corresponds to the ``sip_trunk`` 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.dialogflow_v2.types.SipTrunk: + SipTrunk is the resource that + represents a SIP trunk to connect to + Google Telephony platform SIP trunking + service. + + """ + # 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, sip_trunk] + 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, gcd_sip_trunk.CreateSipTrunkRequest): + request = gcd_sip_trunk.CreateSipTrunkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if sip_trunk is not None: + request.sip_trunk = sip_trunk + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_sip_trunk] + + # 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_sip_trunk( + self, + request: Optional[Union[sip_trunk.DeleteSipTrunkRequest, 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 specified SipTrunk. + + .. 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 dialogflow_v2 + + def sample_delete_sip_trunk(): + # Create a client + client = dialogflow_v2.SipTrunksClient() + + # Initialize request argument(s) + request = dialogflow_v2.DeleteSipTrunkRequest( + name="name_value", + ) + + # Make the request + client.delete_sip_trunk(request=request) + + Args: + request (Union[google.cloud.dialogflow_v2.types.DeleteSipTrunkRequest, dict]): + The request object. The request message for + [SipTrunks.DeleteSipTrunk][google.cloud.dialogflow.v2.SipTrunks.DeleteSipTrunk]. + name (str): + Required. The name of the SIP trunk to delete. Format: + ``projects//locations//sipTrunks/``. + + 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, sip_trunk.DeleteSipTrunkRequest): + request = sip_trunk.DeleteSipTrunkRequest(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_sip_trunk] + + # 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_sip_trunks( + self, + request: Optional[Union[sip_trunk.ListSipTrunksRequest, 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.ListSipTrunksPager: + r"""Returns a list of SipTrunks in the specified + 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 dialogflow_v2 + + def sample_list_sip_trunks(): + # Create a client + client = dialogflow_v2.SipTrunksClient() + + # Initialize request argument(s) + request = dialogflow_v2.ListSipTrunksRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sip_trunks(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.dialogflow_v2.types.ListSipTrunksRequest, dict]): + The request object. The request message for + [SipTrunks.ListSipTrunks][google.cloud.dialogflow.v2.SipTrunks.ListSipTrunks]. + parent (str): + Required. The location to list SIP trunks from. Format: + ``projects//locations/``. + + 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.dialogflow_v2.services.sip_trunks.pagers.ListSipTrunksPager: + The response message for + [SipTrunks.ListSipTrunks][google.cloud.dialogflow.v2.SipTrunks.ListSipTrunks]. + + 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, sip_trunk.ListSipTrunksRequest): + request = sip_trunk.ListSipTrunksRequest(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_sip_trunks] + + # 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.ListSipTrunksPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_sip_trunk( + self, + request: Optional[Union[sip_trunk.GetSipTrunkRequest, 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]]] = (), + ) -> sip_trunk.SipTrunk: + r"""Retrieves the specified SipTrunk. + + .. 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 dialogflow_v2 + + def sample_get_sip_trunk(): + # Create a client + client = dialogflow_v2.SipTrunksClient() + + # Initialize request argument(s) + request = dialogflow_v2.GetSipTrunkRequest( + name="name_value", + ) + + # Make the request + response = client.get_sip_trunk(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.dialogflow_v2.types.GetSipTrunkRequest, dict]): + The request object. The request message for + [SipTrunks.GetSipTrunk][google.cloud.dialogflow.v2.SipTrunks.GetSipTrunk]. + name (str): + Required. The name of the SIP trunk to delete. Format: + ``projects//locations//sipTrunks/``. + + 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.dialogflow_v2.types.SipTrunk: + SipTrunk is the resource that + represents a SIP trunk to connect to + Google Telephony platform SIP trunking + service. + + """ + # 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, sip_trunk.GetSipTrunkRequest): + request = sip_trunk.GetSipTrunkRequest(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_sip_trunk] + + # 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 update_sip_trunk( + self, + request: Optional[Union[gcd_sip_trunk.UpdateSipTrunkRequest, dict]] = None, + *, + sip_trunk: Optional[gcd_sip_trunk.SipTrunk] = 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]]] = (), + ) -> gcd_sip_trunk.SipTrunk: + r"""Updates the specified SipTrunk. + + .. 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 dialogflow_v2 + + def sample_update_sip_trunk(): + # Create a client + client = dialogflow_v2.SipTrunksClient() + + # Initialize request argument(s) + sip_trunk = dialogflow_v2.SipTrunk() + sip_trunk.expected_hostname = ['expected_hostname_value1', 'expected_hostname_value2'] + + request = dialogflow_v2.UpdateSipTrunkRequest( + sip_trunk=sip_trunk, + ) + + # Make the request + response = client.update_sip_trunk(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.dialogflow_v2.types.UpdateSipTrunkRequest, dict]): + The request object. The request message for + [SipTrunks.UpdateSipTrunk][google.cloud.dialogflow.v2.SipTrunks.UpdateSipTrunk]. + sip_trunk (google.cloud.dialogflow_v2.types.SipTrunk): + Required. The SipTrunk to update. + This corresponds to the ``sip_trunk`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The mask 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.dialogflow_v2.types.SipTrunk: + SipTrunk is the resource that + represents a SIP trunk to connect to + Google Telephony platform SIP trunking + service. + + """ + # 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 = [sip_trunk, 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, gcd_sip_trunk.UpdateSipTrunkRequest): + request = gcd_sip_trunk.UpdateSipTrunkRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if sip_trunk is not None: + request.sip_trunk = sip_trunk + 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_sip_trunk] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("sip_trunk.name", request.sip_trunk.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) -> "SipTrunksClient": + 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 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__ = ("SipTrunksClient",) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/sip_trunks/pagers.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/sip_trunks/pagers.py new file mode 100644 index 000000000000..da5409622044 --- /dev/null +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/sip_trunks/pagers.py @@ -0,0 +1,197 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.dialogflow_v2.types import sip_trunk + + +class ListSipTrunksPager: + """A pager for iterating through ``list_sip_trunks`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.ListSipTrunksResponse` object, and + provides an ``__iter__`` method to iterate through its + ``sip_trunks`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSipTrunks`` requests and continue to iterate + through the ``sip_trunks`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.ListSipTrunksResponse` + 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[..., sip_trunk.ListSipTrunksResponse], + request: sip_trunk.ListSipTrunksRequest, + response: sip_trunk.ListSipTrunksResponse, + *, + 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.dialogflow_v2.types.ListSipTrunksRequest): + The initial request object. + response (google.cloud.dialogflow_v2.types.ListSipTrunksResponse): + 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 = sip_trunk.ListSipTrunksRequest(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[sip_trunk.ListSipTrunksResponse]: + 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[sip_trunk.SipTrunk]: + for page in self.pages: + yield from page.sip_trunks + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSipTrunksAsyncPager: + """A pager for iterating through ``list_sip_trunks`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.types.ListSipTrunksResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``sip_trunks`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSipTrunks`` requests and continue to iterate + through the ``sip_trunks`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dialogflow_v2.types.ListSipTrunksResponse` + 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[sip_trunk.ListSipTrunksResponse]], + request: sip_trunk.ListSipTrunksRequest, + response: sip_trunk.ListSipTrunksResponse, + *, + 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.dialogflow_v2.types.ListSipTrunksRequest): + The initial request object. + response (google.cloud.dialogflow_v2.types.ListSipTrunksResponse): + 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 = sip_trunk.ListSipTrunksRequest(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[sip_trunk.ListSipTrunksResponse]: + 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[sip_trunk.SipTrunk]: + async def async_generator(): + async for page in self.pages: + for response in page.sip_trunks: + 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-dialogflow/google/cloud/dialogflow_v2/services/sip_trunks/transports/README.rst b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/sip_trunks/transports/README.rst new file mode 100644 index 000000000000..8351a234d6f9 --- /dev/null +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/sip_trunks/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`SipTrunksTransport` is the ABC for all transports. +- public child `SipTrunksGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `SipTrunksGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseSipTrunksRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `SipTrunksRestTransport` 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-dialogflow/google/cloud/dialogflow_v2/services/sip_trunks/transports/__init__.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/sip_trunks/transports/__init__.py new file mode 100644 index 000000000000..a6d7d37df22f --- /dev/null +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/sip_trunks/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 SipTrunksTransport +from .grpc import SipTrunksGrpcTransport +from .grpc_asyncio import SipTrunksGrpcAsyncIOTransport +from .rest import SipTrunksRestInterceptor, SipTrunksRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SipTrunksTransport]] +_transport_registry["grpc"] = SipTrunksGrpcTransport +_transport_registry["grpc_asyncio"] = SipTrunksGrpcAsyncIOTransport +_transport_registry["rest"] = SipTrunksRestTransport + +__all__ = ( + "SipTrunksTransport", + "SipTrunksGrpcTransport", + "SipTrunksGrpcAsyncIOTransport", + "SipTrunksRestTransport", + "SipTrunksRestInterceptor", +) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/sip_trunks/transports/base.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/sip_trunks/transports/base.py new file mode 100644 index 000000000000..185a9113ccae --- /dev/null +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/sip_trunks/transports/base.py @@ -0,0 +1,304 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +import google.auth # type: ignore +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 +import google.protobuf +from google.protobuf import empty_pb2 # type: ignore + +from google.cloud.dialogflow_v2 import gapic_version as package_version +from google.cloud.dialogflow_v2.types import sip_trunk +from google.cloud.dialogflow_v2.types import sip_trunk as gcd_sip_trunk + +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 SipTrunksTransport(abc.ABC): + """Abstract transport class for SipTrunks.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ) + + DEFAULT_HOST: str = "dialogflow.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: 'dialogflow.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. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # 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_kwargs, quota_project_id=quota_project_id + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # 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.create_sip_trunk: gapic_v1.method.wrap_method( + self.create_sip_trunk, + default_timeout=None, + client_info=client_info, + ), + self.delete_sip_trunk: gapic_v1.method.wrap_method( + self.delete_sip_trunk, + default_timeout=None, + client_info=client_info, + ), + self.list_sip_trunks: gapic_v1.method.wrap_method( + self.list_sip_trunks, + default_timeout=None, + client_info=client_info, + ), + self.get_sip_trunk: gapic_v1.method.wrap_method( + self.get_sip_trunk, + default_timeout=None, + client_info=client_info, + ), + self.update_sip_trunk: gapic_v1.method.wrap_method( + self.update_sip_trunk, + 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.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 create_sip_trunk( + self, + ) -> Callable[ + [gcd_sip_trunk.CreateSipTrunkRequest], + Union[gcd_sip_trunk.SipTrunk, Awaitable[gcd_sip_trunk.SipTrunk]], + ]: + raise NotImplementedError() + + @property + def delete_sip_trunk( + self, + ) -> Callable[ + [sip_trunk.DeleteSipTrunkRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def list_sip_trunks( + self, + ) -> Callable[ + [sip_trunk.ListSipTrunksRequest], + Union[ + sip_trunk.ListSipTrunksResponse, Awaitable[sip_trunk.ListSipTrunksResponse] + ], + ]: + raise NotImplementedError() + + @property + def get_sip_trunk( + self, + ) -> Callable[ + [sip_trunk.GetSipTrunkRequest], + Union[sip_trunk.SipTrunk, Awaitable[sip_trunk.SipTrunk]], + ]: + raise NotImplementedError() + + @property + def update_sip_trunk( + self, + ) -> Callable[ + [gcd_sip_trunk.UpdateSipTrunkRequest], + Union[gcd_sip_trunk.SipTrunk, Awaitable[gcd_sip_trunk.SipTrunk]], + ]: + 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 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__ = ("SipTrunksTransport",) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/sip_trunks/transports/grpc.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/sip_trunks/transports/grpc.py new file mode 100644 index 000000000000..4c0703c18b19 --- /dev/null +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/sip_trunks/transports/grpc.py @@ -0,0 +1,557 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, grpc_helpers +import google.auth # type: ignore +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 import empty_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore + +from google.cloud.dialogflow_v2.types import sip_trunk +from google.cloud.dialogflow_v2.types import sip_trunk as gcd_sip_trunk + +from .base import DEFAULT_CLIENT_INFO, SipTrunksTransport + +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.dialogflow.v2.SipTrunks", + "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.dialogflow.v2.SipTrunks", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class SipTrunksGrpcTransport(SipTrunksTransport): + """gRPC backend transport for SipTrunks. + + Service for managing + [SipTrunks][google.cloud.dialogflow.v2.SipTrunk]. + + 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 = "dialogflow.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: 'dialogflow.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 = "dialogflow.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 create_sip_trunk( + self, + ) -> Callable[[gcd_sip_trunk.CreateSipTrunkRequest], gcd_sip_trunk.SipTrunk]: + r"""Return a callable for the create sip trunk method over gRPC. + + Creates a SipTrunk for a specified location. + + Returns: + Callable[[~.CreateSipTrunkRequest], + ~.SipTrunk]: + 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_sip_trunk" not in self._stubs: + self._stubs["create_sip_trunk"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.v2.SipTrunks/CreateSipTrunk", + request_serializer=gcd_sip_trunk.CreateSipTrunkRequest.serialize, + response_deserializer=gcd_sip_trunk.SipTrunk.deserialize, + ) + return self._stubs["create_sip_trunk"] + + @property + def delete_sip_trunk( + self, + ) -> Callable[[sip_trunk.DeleteSipTrunkRequest], empty_pb2.Empty]: + r"""Return a callable for the delete sip trunk method over gRPC. + + Deletes a specified SipTrunk. + + Returns: + Callable[[~.DeleteSipTrunkRequest], + ~.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_sip_trunk" not in self._stubs: + self._stubs["delete_sip_trunk"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.v2.SipTrunks/DeleteSipTrunk", + request_serializer=sip_trunk.DeleteSipTrunkRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_sip_trunk"] + + @property + def list_sip_trunks( + self, + ) -> Callable[[sip_trunk.ListSipTrunksRequest], sip_trunk.ListSipTrunksResponse]: + r"""Return a callable for the list sip trunks method over gRPC. + + Returns a list of SipTrunks in the specified + location. + + Returns: + Callable[[~.ListSipTrunksRequest], + ~.ListSipTrunksResponse]: + 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_sip_trunks" not in self._stubs: + self._stubs["list_sip_trunks"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.v2.SipTrunks/ListSipTrunks", + request_serializer=sip_trunk.ListSipTrunksRequest.serialize, + response_deserializer=sip_trunk.ListSipTrunksResponse.deserialize, + ) + return self._stubs["list_sip_trunks"] + + @property + def get_sip_trunk( + self, + ) -> Callable[[sip_trunk.GetSipTrunkRequest], sip_trunk.SipTrunk]: + r"""Return a callable for the get sip trunk method over gRPC. + + Retrieves the specified SipTrunk. + + Returns: + Callable[[~.GetSipTrunkRequest], + ~.SipTrunk]: + 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_sip_trunk" not in self._stubs: + self._stubs["get_sip_trunk"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.v2.SipTrunks/GetSipTrunk", + request_serializer=sip_trunk.GetSipTrunkRequest.serialize, + response_deserializer=sip_trunk.SipTrunk.deserialize, + ) + return self._stubs["get_sip_trunk"] + + @property + def update_sip_trunk( + self, + ) -> Callable[[gcd_sip_trunk.UpdateSipTrunkRequest], gcd_sip_trunk.SipTrunk]: + r"""Return a callable for the update sip trunk method over gRPC. + + Updates the specified SipTrunk. + + Returns: + Callable[[~.UpdateSipTrunkRequest], + ~.SipTrunk]: + 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_sip_trunk" not in self._stubs: + self._stubs["update_sip_trunk"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.v2.SipTrunks/UpdateSipTrunk", + request_serializer=gcd_sip_trunk.UpdateSipTrunkRequest.serialize, + response_deserializer=gcd_sip_trunk.SipTrunk.deserialize, + ) + return self._stubs["update_sip_trunk"] + + def close(self): + self._logged_channel.close() + + @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__ = ("SipTrunksGrpcTransport",) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/sip_trunks/transports/grpc_asyncio.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/sip_trunks/transports/grpc_asyncio.py new file mode 100644 index 000000000000..c6e4e8a09d8b --- /dev/null +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/sip_trunks/transports/grpc_asyncio.py @@ -0,0 +1,631 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +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 import empty_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message +import grpc # type: ignore +from grpc.experimental import aio # type: ignore +import proto # type: ignore + +from google.cloud.dialogflow_v2.types import sip_trunk +from google.cloud.dialogflow_v2.types import sip_trunk as gcd_sip_trunk + +from .base import DEFAULT_CLIENT_INFO, SipTrunksTransport +from .grpc import SipTrunksGrpcTransport + +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.dialogflow.v2.SipTrunks", + "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.dialogflow.v2.SipTrunks", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class SipTrunksGrpcAsyncIOTransport(SipTrunksTransport): + """gRPC AsyncIO backend transport for SipTrunks. + + Service for managing + [SipTrunks][google.cloud.dialogflow.v2.SipTrunk]. + + 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 = "dialogflow.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 = "dialogflow.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: 'dialogflow.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 create_sip_trunk( + self, + ) -> Callable[ + [gcd_sip_trunk.CreateSipTrunkRequest], Awaitable[gcd_sip_trunk.SipTrunk] + ]: + r"""Return a callable for the create sip trunk method over gRPC. + + Creates a SipTrunk for a specified location. + + Returns: + Callable[[~.CreateSipTrunkRequest], + Awaitable[~.SipTrunk]]: + 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_sip_trunk" not in self._stubs: + self._stubs["create_sip_trunk"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.v2.SipTrunks/CreateSipTrunk", + request_serializer=gcd_sip_trunk.CreateSipTrunkRequest.serialize, + response_deserializer=gcd_sip_trunk.SipTrunk.deserialize, + ) + return self._stubs["create_sip_trunk"] + + @property + def delete_sip_trunk( + self, + ) -> Callable[[sip_trunk.DeleteSipTrunkRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete sip trunk method over gRPC. + + Deletes a specified SipTrunk. + + Returns: + Callable[[~.DeleteSipTrunkRequest], + 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_sip_trunk" not in self._stubs: + self._stubs["delete_sip_trunk"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.v2.SipTrunks/DeleteSipTrunk", + request_serializer=sip_trunk.DeleteSipTrunkRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_sip_trunk"] + + @property + def list_sip_trunks( + self, + ) -> Callable[ + [sip_trunk.ListSipTrunksRequest], Awaitable[sip_trunk.ListSipTrunksResponse] + ]: + r"""Return a callable for the list sip trunks method over gRPC. + + Returns a list of SipTrunks in the specified + location. + + Returns: + Callable[[~.ListSipTrunksRequest], + Awaitable[~.ListSipTrunksResponse]]: + 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_sip_trunks" not in self._stubs: + self._stubs["list_sip_trunks"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.v2.SipTrunks/ListSipTrunks", + request_serializer=sip_trunk.ListSipTrunksRequest.serialize, + response_deserializer=sip_trunk.ListSipTrunksResponse.deserialize, + ) + return self._stubs["list_sip_trunks"] + + @property + def get_sip_trunk( + self, + ) -> Callable[[sip_trunk.GetSipTrunkRequest], Awaitable[sip_trunk.SipTrunk]]: + r"""Return a callable for the get sip trunk method over gRPC. + + Retrieves the specified SipTrunk. + + Returns: + Callable[[~.GetSipTrunkRequest], + Awaitable[~.SipTrunk]]: + 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_sip_trunk" not in self._stubs: + self._stubs["get_sip_trunk"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.v2.SipTrunks/GetSipTrunk", + request_serializer=sip_trunk.GetSipTrunkRequest.serialize, + response_deserializer=sip_trunk.SipTrunk.deserialize, + ) + return self._stubs["get_sip_trunk"] + + @property + def update_sip_trunk( + self, + ) -> Callable[ + [gcd_sip_trunk.UpdateSipTrunkRequest], Awaitable[gcd_sip_trunk.SipTrunk] + ]: + r"""Return a callable for the update sip trunk method over gRPC. + + Updates the specified SipTrunk. + + Returns: + Callable[[~.UpdateSipTrunkRequest], + Awaitable[~.SipTrunk]]: + 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_sip_trunk" not in self._stubs: + self._stubs["update_sip_trunk"] = self._logged_channel.unary_unary( + "/google.cloud.dialogflow.v2.SipTrunks/UpdateSipTrunk", + request_serializer=gcd_sip_trunk.UpdateSipTrunkRequest.serialize, + response_deserializer=gcd_sip_trunk.SipTrunk.deserialize, + ) + return self._stubs["update_sip_trunk"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.create_sip_trunk: self._wrap_method( + self.create_sip_trunk, + default_timeout=None, + client_info=client_info, + ), + self.delete_sip_trunk: self._wrap_method( + self.delete_sip_trunk, + default_timeout=None, + client_info=client_info, + ), + self.list_sip_trunks: self._wrap_method( + self.list_sip_trunks, + default_timeout=None, + client_info=client_info, + ), + self.get_sip_trunk: self._wrap_method( + self.get_sip_trunk, + default_timeout=None, + client_info=client_info, + ), + self.update_sip_trunk: self._wrap_method( + self.update_sip_trunk, + 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.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 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__ = ("SipTrunksGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/sip_trunks/transports/rest.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/sip_trunks/transports/rest.py new file mode 100644 index 000000000000..6b6c0135029e --- /dev/null +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/sip_trunks/transports/rest.py @@ -0,0 +1,2014 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +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 +import google.protobuf +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.dialogflow_v2.types import sip_trunk +from google.cloud.dialogflow_v2.types import sip_trunk as gcd_sip_trunk + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseSipTrunksRestTransport + +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 SipTrunksRestInterceptor: + """Interceptor for SipTrunks. + + 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 SipTrunksRestTransport. + + .. code-block:: python + class MyCustomSipTrunksInterceptor(SipTrunksRestInterceptor): + def pre_create_sip_trunk(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_sip_trunk(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_sip_trunk(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_sip_trunk(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_sip_trunk(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_sip_trunks(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_sip_trunks(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_sip_trunk(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_sip_trunk(self, response): + logging.log(f"Received response: {response}") + return response + + transport = SipTrunksRestTransport(interceptor=MyCustomSipTrunksInterceptor()) + client = SipTrunksClient(transport=transport) + + + """ + + def pre_create_sip_trunk( + self, + request: gcd_sip_trunk.CreateSipTrunkRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcd_sip_trunk.CreateSipTrunkRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_sip_trunk + + Override in a subclass to manipulate the request or metadata + before they are sent to the SipTrunks server. + """ + return request, metadata + + def post_create_sip_trunk( + self, response: gcd_sip_trunk.SipTrunk + ) -> gcd_sip_trunk.SipTrunk: + """Post-rpc interceptor for create_sip_trunk + + DEPRECATED. Please use the `post_create_sip_trunk_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SipTrunks server but before + it is returned to user code. This `post_create_sip_trunk` interceptor runs + before the `post_create_sip_trunk_with_metadata` interceptor. + """ + return response + + def post_create_sip_trunk_with_metadata( + self, + response: gcd_sip_trunk.SipTrunk, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gcd_sip_trunk.SipTrunk, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_sip_trunk + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SipTrunks server but before it is returned to user code. + + We recommend only using this `post_create_sip_trunk_with_metadata` + interceptor in new development instead of the `post_create_sip_trunk` interceptor. + When both interceptors are used, this `post_create_sip_trunk_with_metadata` interceptor runs after the + `post_create_sip_trunk` interceptor. The (possibly modified) response returned by + `post_create_sip_trunk` will be passed to + `post_create_sip_trunk_with_metadata`. + """ + return response, metadata + + def pre_delete_sip_trunk( + self, + request: sip_trunk.DeleteSipTrunkRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + sip_trunk.DeleteSipTrunkRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_sip_trunk + + Override in a subclass to manipulate the request or metadata + before they are sent to the SipTrunks server. + """ + return request, metadata + + def pre_get_sip_trunk( + self, + request: sip_trunk.GetSipTrunkRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[sip_trunk.GetSipTrunkRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_sip_trunk + + Override in a subclass to manipulate the request or metadata + before they are sent to the SipTrunks server. + """ + return request, metadata + + def post_get_sip_trunk(self, response: sip_trunk.SipTrunk) -> sip_trunk.SipTrunk: + """Post-rpc interceptor for get_sip_trunk + + DEPRECATED. Please use the `post_get_sip_trunk_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SipTrunks server but before + it is returned to user code. This `post_get_sip_trunk` interceptor runs + before the `post_get_sip_trunk_with_metadata` interceptor. + """ + return response + + def post_get_sip_trunk_with_metadata( + self, + response: sip_trunk.SipTrunk, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[sip_trunk.SipTrunk, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_sip_trunk + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SipTrunks server but before it is returned to user code. + + We recommend only using this `post_get_sip_trunk_with_metadata` + interceptor in new development instead of the `post_get_sip_trunk` interceptor. + When both interceptors are used, this `post_get_sip_trunk_with_metadata` interceptor runs after the + `post_get_sip_trunk` interceptor. The (possibly modified) response returned by + `post_get_sip_trunk` will be passed to + `post_get_sip_trunk_with_metadata`. + """ + return response, metadata + + def pre_list_sip_trunks( + self, + request: sip_trunk.ListSipTrunksRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[sip_trunk.ListSipTrunksRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_sip_trunks + + Override in a subclass to manipulate the request or metadata + before they are sent to the SipTrunks server. + """ + return request, metadata + + def post_list_sip_trunks( + self, response: sip_trunk.ListSipTrunksResponse + ) -> sip_trunk.ListSipTrunksResponse: + """Post-rpc interceptor for list_sip_trunks + + DEPRECATED. Please use the `post_list_sip_trunks_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SipTrunks server but before + it is returned to user code. This `post_list_sip_trunks` interceptor runs + before the `post_list_sip_trunks_with_metadata` interceptor. + """ + return response + + def post_list_sip_trunks_with_metadata( + self, + response: sip_trunk.ListSipTrunksResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + sip_trunk.ListSipTrunksResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_sip_trunks + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SipTrunks server but before it is returned to user code. + + We recommend only using this `post_list_sip_trunks_with_metadata` + interceptor in new development instead of the `post_list_sip_trunks` interceptor. + When both interceptors are used, this `post_list_sip_trunks_with_metadata` interceptor runs after the + `post_list_sip_trunks` interceptor. The (possibly modified) response returned by + `post_list_sip_trunks` will be passed to + `post_list_sip_trunks_with_metadata`. + """ + return response, metadata + + def pre_update_sip_trunk( + self, + request: gcd_sip_trunk.UpdateSipTrunkRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcd_sip_trunk.UpdateSipTrunkRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_sip_trunk + + Override in a subclass to manipulate the request or metadata + before they are sent to the SipTrunks server. + """ + return request, metadata + + def post_update_sip_trunk( + self, response: gcd_sip_trunk.SipTrunk + ) -> gcd_sip_trunk.SipTrunk: + """Post-rpc interceptor for update_sip_trunk + + DEPRECATED. Please use the `post_update_sip_trunk_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SipTrunks server but before + it is returned to user code. This `post_update_sip_trunk` interceptor runs + before the `post_update_sip_trunk_with_metadata` interceptor. + """ + return response + + def post_update_sip_trunk_with_metadata( + self, + response: gcd_sip_trunk.SipTrunk, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gcd_sip_trunk.SipTrunk, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_sip_trunk + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SipTrunks server but before it is returned to user code. + + We recommend only using this `post_update_sip_trunk_with_metadata` + interceptor in new development instead of the `post_update_sip_trunk` interceptor. + When both interceptors are used, this `post_update_sip_trunk_with_metadata` interceptor runs after the + `post_update_sip_trunk` interceptor. The (possibly modified) response returned by + `post_update_sip_trunk` will be passed to + `post_update_sip_trunk_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 SipTrunks 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 SipTrunks 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 SipTrunks 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 SipTrunks 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 SipTrunks 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 SipTrunks 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 SipTrunks 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 SipTrunks 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 SipTrunks 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 SipTrunks server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class SipTrunksRestStub: + _session: AuthorizedSession + _host: str + _interceptor: SipTrunksRestInterceptor + + +class SipTrunksRestTransport(_BaseSipTrunksRestTransport): + """REST backend synchronous transport for SipTrunks. + + Service for managing + [SipTrunks][google.cloud.dialogflow.v2.SipTrunk]. + + 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 = "dialogflow.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[SipTrunksRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'dialogflow.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 SipTrunksRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateSipTrunk( + _BaseSipTrunksRestTransport._BaseCreateSipTrunk, SipTrunksRestStub + ): + def __hash__(self): + return hash("SipTrunksRestTransport.CreateSipTrunk") + + @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: gcd_sip_trunk.CreateSipTrunkRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcd_sip_trunk.SipTrunk: + r"""Call the create sip trunk method over HTTP. + + Args: + request (~.gcd_sip_trunk.CreateSipTrunkRequest): + The request object. The request message for + [SipTrunks.CreateSipTrunk][google.cloud.dialogflow.v2.SipTrunks.CreateSipTrunk]. + 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: + ~.gcd_sip_trunk.SipTrunk: + SipTrunk is the resource that + represents a SIP trunk to connect to + Google Telephony platform SIP trunking + service. + + """ + + http_options = ( + _BaseSipTrunksRestTransport._BaseCreateSipTrunk._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_sip_trunk( + request, metadata + ) + transcoded_request = ( + _BaseSipTrunksRestTransport._BaseCreateSipTrunk._get_transcoded_request( + http_options, request + ) + ) + + body = ( + _BaseSipTrunksRestTransport._BaseCreateSipTrunk._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSipTrunksRestTransport._BaseCreateSipTrunk._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.dialogflow_v2.SipTrunksClient.CreateSipTrunk", + extra={ + "serviceName": "google.cloud.dialogflow.v2.SipTrunks", + "rpcName": "CreateSipTrunk", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SipTrunksRestTransport._CreateSipTrunk._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 = gcd_sip_trunk.SipTrunk() + pb_resp = gcd_sip_trunk.SipTrunk.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_sip_trunk(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_sip_trunk_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gcd_sip_trunk.SipTrunk.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.dialogflow_v2.SipTrunksClient.create_sip_trunk", + extra={ + "serviceName": "google.cloud.dialogflow.v2.SipTrunks", + "rpcName": "CreateSipTrunk", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteSipTrunk( + _BaseSipTrunksRestTransport._BaseDeleteSipTrunk, SipTrunksRestStub + ): + def __hash__(self): + return hash("SipTrunksRestTransport.DeleteSipTrunk") + + @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: sip_trunk.DeleteSipTrunkRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete sip trunk method over HTTP. + + Args: + request (~.sip_trunk.DeleteSipTrunkRequest): + The request object. The request message for + [SipTrunks.DeleteSipTrunk][google.cloud.dialogflow.v2.SipTrunks.DeleteSipTrunk]. + 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 = ( + _BaseSipTrunksRestTransport._BaseDeleteSipTrunk._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_sip_trunk( + request, metadata + ) + transcoded_request = ( + _BaseSipTrunksRestTransport._BaseDeleteSipTrunk._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSipTrunksRestTransport._BaseDeleteSipTrunk._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.dialogflow_v2.SipTrunksClient.DeleteSipTrunk", + extra={ + "serviceName": "google.cloud.dialogflow.v2.SipTrunks", + "rpcName": "DeleteSipTrunk", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SipTrunksRestTransport._DeleteSipTrunk._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 _GetSipTrunk(_BaseSipTrunksRestTransport._BaseGetSipTrunk, SipTrunksRestStub): + def __hash__(self): + return hash("SipTrunksRestTransport.GetSipTrunk") + + @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: sip_trunk.GetSipTrunkRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> sip_trunk.SipTrunk: + r"""Call the get sip trunk method over HTTP. + + Args: + request (~.sip_trunk.GetSipTrunkRequest): + The request object. The request message for + [SipTrunks.GetSipTrunk][google.cloud.dialogflow.v2.SipTrunks.GetSipTrunk]. + 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: + ~.sip_trunk.SipTrunk: + SipTrunk is the resource that + represents a SIP trunk to connect to + Google Telephony platform SIP trunking + service. + + """ + + http_options = ( + _BaseSipTrunksRestTransport._BaseGetSipTrunk._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_sip_trunk(request, metadata) + transcoded_request = ( + _BaseSipTrunksRestTransport._BaseGetSipTrunk._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSipTrunksRestTransport._BaseGetSipTrunk._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.dialogflow_v2.SipTrunksClient.GetSipTrunk", + extra={ + "serviceName": "google.cloud.dialogflow.v2.SipTrunks", + "rpcName": "GetSipTrunk", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SipTrunksRestTransport._GetSipTrunk._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 = sip_trunk.SipTrunk() + pb_resp = sip_trunk.SipTrunk.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_sip_trunk(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_sip_trunk_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = sip_trunk.SipTrunk.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.dialogflow_v2.SipTrunksClient.get_sip_trunk", + extra={ + "serviceName": "google.cloud.dialogflow.v2.SipTrunks", + "rpcName": "GetSipTrunk", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListSipTrunks( + _BaseSipTrunksRestTransport._BaseListSipTrunks, SipTrunksRestStub + ): + def __hash__(self): + return hash("SipTrunksRestTransport.ListSipTrunks") + + @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: sip_trunk.ListSipTrunksRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> sip_trunk.ListSipTrunksResponse: + r"""Call the list sip trunks method over HTTP. + + Args: + request (~.sip_trunk.ListSipTrunksRequest): + The request object. The request message for + [SipTrunks.ListSipTrunks][google.cloud.dialogflow.v2.SipTrunks.ListSipTrunks]. + 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: + ~.sip_trunk.ListSipTrunksResponse: + The response message for + [SipTrunks.ListSipTrunks][google.cloud.dialogflow.v2.SipTrunks.ListSipTrunks]. + + """ + + http_options = ( + _BaseSipTrunksRestTransport._BaseListSipTrunks._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_sip_trunks(request, metadata) + transcoded_request = ( + _BaseSipTrunksRestTransport._BaseListSipTrunks._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSipTrunksRestTransport._BaseListSipTrunks._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.dialogflow_v2.SipTrunksClient.ListSipTrunks", + extra={ + "serviceName": "google.cloud.dialogflow.v2.SipTrunks", + "rpcName": "ListSipTrunks", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SipTrunksRestTransport._ListSipTrunks._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 = sip_trunk.ListSipTrunksResponse() + pb_resp = sip_trunk.ListSipTrunksResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_sip_trunks(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_sip_trunks_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = sip_trunk.ListSipTrunksResponse.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.dialogflow_v2.SipTrunksClient.list_sip_trunks", + extra={ + "serviceName": "google.cloud.dialogflow.v2.SipTrunks", + "rpcName": "ListSipTrunks", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateSipTrunk( + _BaseSipTrunksRestTransport._BaseUpdateSipTrunk, SipTrunksRestStub + ): + def __hash__(self): + return hash("SipTrunksRestTransport.UpdateSipTrunk") + + @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: gcd_sip_trunk.UpdateSipTrunkRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcd_sip_trunk.SipTrunk: + r"""Call the update sip trunk method over HTTP. + + Args: + request (~.gcd_sip_trunk.UpdateSipTrunkRequest): + The request object. The request message for + [SipTrunks.UpdateSipTrunk][google.cloud.dialogflow.v2.SipTrunks.UpdateSipTrunk]. + 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: + ~.gcd_sip_trunk.SipTrunk: + SipTrunk is the resource that + represents a SIP trunk to connect to + Google Telephony platform SIP trunking + service. + + """ + + http_options = ( + _BaseSipTrunksRestTransport._BaseUpdateSipTrunk._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_sip_trunk( + request, metadata + ) + transcoded_request = ( + _BaseSipTrunksRestTransport._BaseUpdateSipTrunk._get_transcoded_request( + http_options, request + ) + ) + + body = ( + _BaseSipTrunksRestTransport._BaseUpdateSipTrunk._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSipTrunksRestTransport._BaseUpdateSipTrunk._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.dialogflow_v2.SipTrunksClient.UpdateSipTrunk", + extra={ + "serviceName": "google.cloud.dialogflow.v2.SipTrunks", + "rpcName": "UpdateSipTrunk", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SipTrunksRestTransport._UpdateSipTrunk._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 = gcd_sip_trunk.SipTrunk() + pb_resp = gcd_sip_trunk.SipTrunk.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_sip_trunk(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_sip_trunk_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gcd_sip_trunk.SipTrunk.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.dialogflow_v2.SipTrunksClient.update_sip_trunk", + extra={ + "serviceName": "google.cloud.dialogflow.v2.SipTrunks", + "rpcName": "UpdateSipTrunk", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_sip_trunk( + self, + ) -> Callable[[gcd_sip_trunk.CreateSipTrunkRequest], gcd_sip_trunk.SipTrunk]: + # 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._CreateSipTrunk(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_sip_trunk( + self, + ) -> Callable[[sip_trunk.DeleteSipTrunkRequest], 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._DeleteSipTrunk(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_sip_trunk( + self, + ) -> Callable[[sip_trunk.GetSipTrunkRequest], sip_trunk.SipTrunk]: + # 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._GetSipTrunk(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_sip_trunks( + self, + ) -> Callable[[sip_trunk.ListSipTrunksRequest], sip_trunk.ListSipTrunksResponse]: + # 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._ListSipTrunks(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_sip_trunk( + self, + ) -> Callable[[gcd_sip_trunk.UpdateSipTrunkRequest], gcd_sip_trunk.SipTrunk]: + # 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._UpdateSipTrunk(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(_BaseSipTrunksRestTransport._BaseGetLocation, SipTrunksRestStub): + def __hash__(self): + return hash("SipTrunksRestTransport.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 = ( + _BaseSipTrunksRestTransport._BaseGetLocation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_location(request, metadata) + transcoded_request = ( + _BaseSipTrunksRestTransport._BaseGetLocation._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSipTrunksRestTransport._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.dialogflow_v2.SipTrunksClient.GetLocation", + extra={ + "serviceName": "google.cloud.dialogflow.v2.SipTrunks", + "rpcName": "GetLocation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SipTrunksRestTransport._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.dialogflow_v2.SipTrunksAsyncClient.GetLocation", + extra={ + "serviceName": "google.cloud.dialogflow.v2.SipTrunks", + "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( + _BaseSipTrunksRestTransport._BaseListLocations, SipTrunksRestStub + ): + def __hash__(self): + return hash("SipTrunksRestTransport.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 = ( + _BaseSipTrunksRestTransport._BaseListLocations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + transcoded_request = ( + _BaseSipTrunksRestTransport._BaseListLocations._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSipTrunksRestTransport._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.dialogflow_v2.SipTrunksClient.ListLocations", + extra={ + "serviceName": "google.cloud.dialogflow.v2.SipTrunks", + "rpcName": "ListLocations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SipTrunksRestTransport._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.dialogflow_v2.SipTrunksAsyncClient.ListLocations", + extra={ + "serviceName": "google.cloud.dialogflow.v2.SipTrunks", + "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( + _BaseSipTrunksRestTransport._BaseCancelOperation, SipTrunksRestStub + ): + def __hash__(self): + return hash("SipTrunksRestTransport.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), + ) + 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 = ( + _BaseSipTrunksRestTransport._BaseCancelOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + transcoded_request = _BaseSipTrunksRestTransport._BaseCancelOperation._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = ( + _BaseSipTrunksRestTransport._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.dialogflow_v2.SipTrunksClient.CancelOperation", + extra={ + "serviceName": "google.cloud.dialogflow.v2.SipTrunks", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SipTrunksRestTransport._CancelOperation._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_cancel_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation( + _BaseSipTrunksRestTransport._BaseGetOperation, SipTrunksRestStub + ): + def __hash__(self): + return hash("SipTrunksRestTransport.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 = ( + _BaseSipTrunksRestTransport._BaseGetOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = ( + _BaseSipTrunksRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSipTrunksRestTransport._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.dialogflow_v2.SipTrunksClient.GetOperation", + extra={ + "serviceName": "google.cloud.dialogflow.v2.SipTrunks", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SipTrunksRestTransport._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.dialogflow_v2.SipTrunksAsyncClient.GetOperation", + extra={ + "serviceName": "google.cloud.dialogflow.v2.SipTrunks", + "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( + _BaseSipTrunksRestTransport._BaseListOperations, SipTrunksRestStub + ): + def __hash__(self): + return hash("SipTrunksRestTransport.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 = ( + _BaseSipTrunksRestTransport._BaseListOperations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = ( + _BaseSipTrunksRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSipTrunksRestTransport._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.dialogflow_v2.SipTrunksClient.ListOperations", + extra={ + "serviceName": "google.cloud.dialogflow.v2.SipTrunks", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SipTrunksRestTransport._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.dialogflow_v2.SipTrunksAsyncClient.ListOperations", + extra={ + "serviceName": "google.cloud.dialogflow.v2.SipTrunks", + "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__ = ("SipTrunksRestTransport",) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/sip_trunks/transports/rest_base.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/sip_trunks/transports/rest_base.py new file mode 100644 index 000000000000..887081a3e088 --- /dev/null +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/sip_trunks/transports/rest_base.py @@ -0,0 +1,487 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 empty_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.dialogflow_v2.types import sip_trunk +from google.cloud.dialogflow_v2.types import sip_trunk as gcd_sip_trunk + +from .base import DEFAULT_CLIENT_INFO, SipTrunksTransport + + +class _BaseSipTrunksRestTransport(SipTrunksTransport): + """Base REST backend transport for SipTrunks. + + 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 = "dialogflow.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: 'dialogflow.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 _BaseCreateSipTrunk: + 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": "/v2/{parent=projects/*/locations/*}/sipTrunks", + "body": "sip_trunk", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcd_sip_trunk.CreateSipTrunkRequest.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( + _BaseSipTrunksRestTransport._BaseCreateSipTrunk._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteSipTrunk: + 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": "/v2/{name=projects/*/locations/*/sipTrunks/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = sip_trunk.DeleteSipTrunkRequest.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( + _BaseSipTrunksRestTransport._BaseDeleteSipTrunk._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetSipTrunk: + 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": "/v2/{name=projects/*/locations/*/sipTrunks/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = sip_trunk.GetSipTrunkRequest.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( + _BaseSipTrunksRestTransport._BaseGetSipTrunk._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListSipTrunks: + 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": "/v2/{parent=projects/*/locations/*}/sipTrunks", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = sip_trunk.ListSipTrunksRequest.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( + _BaseSipTrunksRestTransport._BaseListSipTrunks._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateSipTrunk: + 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": "/v2/{sip_trunk.name=projects/*/locations/*/sipTrunks/*}", + "body": "sip_trunk", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcd_sip_trunk.UpdateSipTrunkRequest.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( + _BaseSipTrunksRestTransport._BaseUpdateSipTrunk._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": "/v2/{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": "/v2/{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": "/v2/{name=projects/*/operations/*}:cancel", + }, + { + "method": "post", + "uri": "/v2/{name=projects/*/locations/*/operations/*}:cancel", + }, + ] + 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": "/v2/{name=projects/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2/{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": "/v2/{name=projects/*}/operations", + }, + { + "method": "get", + "uri": "/v2/{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__ = ("_BaseSipTrunksRestTransport",) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/tools/__init__.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/tools/__init__.py new file mode 100644 index 000000000000..ca7fdb7c7f9d --- /dev/null +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/tools/__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 ToolsAsyncClient +from .client import ToolsClient + +__all__ = ( + "ToolsClient", + "ToolsAsyncClient", +) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/tools/async_client.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/tools/async_client.py new file mode 100644 index 000000000000..003c135c0111 --- /dev/null +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/tools/async_client.py @@ -0,0 +1,1181 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +import logging as std_logging +import re +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +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 +import google.protobuf + +from google.cloud.dialogflow_v2 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.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.dialogflow_v2.services.tools import pagers +from google.cloud.dialogflow_v2.types import tool +from google.cloud.dialogflow_v2.types import tool as gcd_tool + +from .client import ToolsClient +from .transports.base import DEFAULT_CLIENT_INFO, ToolsTransport +from .transports.grpc_asyncio import ToolsGrpcAsyncIOTransport + +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 ToolsAsyncClient: + """Tool Service for LLM powered Agent Assist. Tools can be used + to interact with remote APIs (e.g. fetching orders) to retrieve + additional information as input to LLM. + """ + + _client: ToolsClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = ToolsClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ToolsClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = ToolsClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = ToolsClient._DEFAULT_UNIVERSE + + secret_version_path = staticmethod(ToolsClient.secret_version_path) + parse_secret_version_path = staticmethod(ToolsClient.parse_secret_version_path) + service_path = staticmethod(ToolsClient.service_path) + parse_service_path = staticmethod(ToolsClient.parse_service_path) + tool_path = staticmethod(ToolsClient.tool_path) + parse_tool_path = staticmethod(ToolsClient.parse_tool_path) + common_billing_account_path = staticmethod(ToolsClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod( + ToolsClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(ToolsClient.common_folder_path) + parse_common_folder_path = staticmethod(ToolsClient.parse_common_folder_path) + common_organization_path = staticmethod(ToolsClient.common_organization_path) + parse_common_organization_path = staticmethod( + ToolsClient.parse_common_organization_path + ) + common_project_path = staticmethod(ToolsClient.common_project_path) + parse_common_project_path = staticmethod(ToolsClient.parse_common_project_path) + common_location_path = staticmethod(ToolsClient.common_location_path) + parse_common_location_path = staticmethod(ToolsClient.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: + ToolsAsyncClient: The constructed client. + """ + return ToolsClient.from_service_account_info.__func__(ToolsAsyncClient, info, *args, **kwargs) # type: ignore + + @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: + ToolsAsyncClient: The constructed client. + """ + return ToolsClient.from_service_account_file.__func__(ToolsAsyncClient, filename, *args, **kwargs) # type: ignore + + 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 ToolsClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> ToolsTransport: + """Returns the transport used by the client instance. + + Returns: + ToolsTransport: 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 = ToolsClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, ToolsTransport, Callable[..., ToolsTransport]] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the tools 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,ToolsTransport,Callable[..., ToolsTransport]]]): + 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 ToolsTransport 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 = ToolsClient( + 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.dialogflow_v2.ToolsAsyncClient`.", + extra={ + "serviceName": "google.cloud.dialogflow.v2.Tools", + "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.dialogflow.v2.Tools", + "credentialsType": None, + }, + ) + + async def create_tool( + self, + request: Optional[Union[gcd_tool.CreateToolRequest, dict]] = None, + *, + parent: Optional[str] = None, + tool: Optional[gcd_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]]] = (), + ) -> gcd_tool.Tool: + r"""Creates a 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 dialogflow_v2 + + async def sample_create_tool(): + # Create a client + client = dialogflow_v2.ToolsAsyncClient() + + # Initialize request argument(s) + tool = dialogflow_v2.Tool() + tool.extension_spec.name = "name_value" + tool.tool_key = "tool_key_value" + + request = dialogflow_v2.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.dialogflow_v2.types.CreateToolRequest, dict]]): + The request object. Request message of CreateTool. + parent (:class:`str`): + Required. The project/location to create tool for. + Format: + ``projects//locations/`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tool (:class:`google.cloud.dialogflow_v2.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. + + The tool ID must be compliant with the regression + formula ``[a-zA-Z][a-zA-Z0-9_-]*`` with the characters + length in range of [3,64]. If the field is not provide, + an Id will be auto-generated. If the field is provided, + the caller is responsible for + + 1. the uniqueness of the ID, otherwise the request will + be rejected. + 2. the consistency for whether to use custom ID or not + under a project to better ensure uniqueness. + + 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.dialogflow_v2.types.Tool: + Represents a tool. + """ + # 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, gcd_tool.CreateToolRequest): + request = gcd_tool.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 get_tool( + self, + request: Optional[Union[tool.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"""Retrieves a 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 dialogflow_v2 + + async def sample_get_tool(): + # Create a client + client = dialogflow_v2.ToolsAsyncClient() + + # Initialize request argument(s) + request = dialogflow_v2.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.dialogflow_v2.types.GetToolRequest, dict]]): + The request object. Request message of GetTool. + name (:class:`str`): + Required. The tool resource name to retrieve. Format: + ``projects//locations//tools/`` + + 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.dialogflow_v2.types.Tool: + Represents a tool. + """ + # 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, tool.GetToolRequest): + request = tool.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_tools( + self, + request: Optional[Union[tool.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. + + .. 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 dialogflow_v2 + + async def sample_list_tools(): + # Create a client + client = dialogflow_v2.ToolsAsyncClient() + + # Initialize request argument(s) + request = dialogflow_v2.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.dialogflow_v2.types.ListToolsRequest, dict]]): + The request object. Request message of ListTools. + parent (:class:`str`): + Required. The project/location to list tools for. + Format: + ``projects//locations/`` + + 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.dialogflow_v2.services.tools.pagers.ListToolsAsyncPager: + Response of 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, tool.ListToolsRequest): + request = tool.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 delete_tool( + self, + request: Optional[Union[tool.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 a 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 dialogflow_v2 + + async def sample_delete_tool(): + # Create a client + client = dialogflow_v2.ToolsAsyncClient() + + # Initialize request argument(s) + request = dialogflow_v2.DeleteToolRequest( + name="name_value", + ) + + # Make the request + await client.delete_tool(request=request) + + Args: + request (Optional[Union[google.cloud.dialogflow_v2.types.DeleteToolRequest, dict]]): + The request object. Request of DeleteTool. + name (:class:`str`): + Required. The tool resource name to delete. Format: + ``projects//locations//tools/`` + + 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, tool.DeleteToolRequest): + request = tool.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 update_tool( + self, + request: Optional[Union[gcd_tool.UpdateToolRequest, dict]] = None, + *, + tool: Optional[gcd_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]]] = (), + ) -> gcd_tool.Tool: + r"""Updates a 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 dialogflow_v2 + + async def sample_update_tool(): + # Create a client + client = dialogflow_v2.ToolsAsyncClient() + + # Initialize request argument(s) + tool = dialogflow_v2.Tool() + tool.extension_spec.name = "name_value" + tool.tool_key = "tool_key_value" + + request = dialogflow_v2.UpdateToolRequest( + tool=tool, + ) + + # Make the request + response = await client.update_tool(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.dialogflow_v2.types.UpdateToolRequest, dict]]): + The request object. Request of UpdateTool. + tool (:class:`google.cloud.dialogflow_v2.types.Tool`): + Required. The tool to update. + The name field of tool is to identify + 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. 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.dialogflow_v2.types.Tool: + Represents a tool. + """ + # 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, gcd_tool.UpdateToolRequest): + request = gcd_tool.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 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 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) -> "ToolsAsyncClient": + 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__ = ("ToolsAsyncClient",) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/tools/client.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/tools/client.py new file mode 100644 index 000000000000..644e230bcaa1 --- /dev/null +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/tools/client.py @@ -0,0 +1,1678 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 http import HTTPStatus +import json +import logging as std_logging +import os +import re +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) +import warnings + +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 +import google.protobuf + +from google.cloud.dialogflow_v2 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.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.dialogflow_v2.services.tools import pagers +from google.cloud.dialogflow_v2.types import tool +from google.cloud.dialogflow_v2.types import tool as gcd_tool + +from .transports.base import DEFAULT_CLIENT_INFO, ToolsTransport +from .transports.grpc import ToolsGrpcTransport +from .transports.grpc_asyncio import ToolsGrpcAsyncIOTransport +from .transports.rest import ToolsRestTransport + + +class ToolsClientMeta(type): + """Metaclass for the Tools 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[ToolsTransport]] + _transport_registry["grpc"] = ToolsGrpcTransport + _transport_registry["grpc_asyncio"] = ToolsGrpcAsyncIOTransport + _transport_registry["rest"] = ToolsRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[ToolsTransport]: + """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 ToolsClient(metaclass=ToolsClientMeta): + """Tool Service for LLM powered Agent Assist. Tools can be used + to interact with remote APIs (e.g. fetching orders) to retrieve + additional information as input to LLM. + """ + + @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 = "dialogflow.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "dialogflow.{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: + ToolsClient: 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: + ToolsClient: 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) -> ToolsTransport: + """Returns the transport used by the client instance. + + Returns: + ToolsTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def secret_version_path( + project: str, + secret: str, + version: str, + ) -> str: + """Returns a fully-qualified secret_version string.""" + return "projects/{project}/secrets/{secret}/versions/{version}".format( + project=project, + secret=secret, + version=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, + tool: str, + ) -> str: + """Returns a fully-qualified tool string.""" + return "projects/{project}/locations/{location}/tools/{tool}".format( + project=project, + location=location, + 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.+?)/tools/(?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 = ToolsClient._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 = ToolsClient._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 = ToolsClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = ToolsClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ToolsClient._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 = ToolsClient._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, ToolsTransport, Callable[..., ToolsTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the tools 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,ToolsTransport,Callable[..., ToolsTransport]]]): + 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 ToolsTransport 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, + ) = ToolsClient._read_environment_variables() + self._client_cert_source = ToolsClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = ToolsClient._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, ToolsTransport) + if transport_provided: + # transport is a ToolsTransport 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(ToolsTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = self._api_endpoint or ToolsClient._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[ToolsTransport], Callable[..., ToolsTransport] + ] = ( + ToolsClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., ToolsTransport], 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.dialogflow_v2.ToolsClient`.", + extra={ + "serviceName": "google.cloud.dialogflow.v2.Tools", + "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.dialogflow.v2.Tools", + "credentialsType": None, + }, + ) + + def create_tool( + self, + request: Optional[Union[gcd_tool.CreateToolRequest, dict]] = None, + *, + parent: Optional[str] = None, + tool: Optional[gcd_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]]] = (), + ) -> gcd_tool.Tool: + r"""Creates a 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 dialogflow_v2 + + def sample_create_tool(): + # Create a client + client = dialogflow_v2.ToolsClient() + + # Initialize request argument(s) + tool = dialogflow_v2.Tool() + tool.extension_spec.name = "name_value" + tool.tool_key = "tool_key_value" + + request = dialogflow_v2.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.dialogflow_v2.types.CreateToolRequest, dict]): + The request object. Request message of CreateTool. + parent (str): + Required. The project/location to create tool for. + Format: + ``projects//locations/`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + tool (google.cloud.dialogflow_v2.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. + + The tool ID must be compliant with the regression + formula ``[a-zA-Z][a-zA-Z0-9_-]*`` with the characters + length in range of [3,64]. If the field is not provide, + an Id will be auto-generated. If the field is provided, + the caller is responsible for + + 1. the uniqueness of the ID, otherwise the request will + be rejected. + 2. the consistency for whether to use custom ID or not + under a project to better ensure uniqueness. + + 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.dialogflow_v2.types.Tool: + Represents a tool. + """ + # 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, gcd_tool.CreateToolRequest): + request = gcd_tool.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 get_tool( + self, + request: Optional[Union[tool.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"""Retrieves a 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 dialogflow_v2 + + def sample_get_tool(): + # Create a client + client = dialogflow_v2.ToolsClient() + + # Initialize request argument(s) + request = dialogflow_v2.GetToolRequest( + name="name_value", + ) + + # Make the request + response = client.get_tool(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.dialogflow_v2.types.GetToolRequest, dict]): + The request object. Request message of GetTool. + name (str): + Required. The tool resource name to retrieve. Format: + ``projects//locations//tools/`` + + 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.dialogflow_v2.types.Tool: + Represents a tool. + """ + # 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, tool.GetToolRequest): + request = tool.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_tools( + self, + request: Optional[Union[tool.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. + + .. 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 dialogflow_v2 + + def sample_list_tools(): + # Create a client + client = dialogflow_v2.ToolsClient() + + # Initialize request argument(s) + request = dialogflow_v2.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.dialogflow_v2.types.ListToolsRequest, dict]): + The request object. Request message of ListTools. + parent (str): + Required. The project/location to list tools for. + Format: + ``projects//locations/`` + + 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.dialogflow_v2.services.tools.pagers.ListToolsPager: + Response of 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, tool.ListToolsRequest): + request = tool.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 delete_tool( + self, + request: Optional[Union[tool.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 a 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 dialogflow_v2 + + def sample_delete_tool(): + # Create a client + client = dialogflow_v2.ToolsClient() + + # Initialize request argument(s) + request = dialogflow_v2.DeleteToolRequest( + name="name_value", + ) + + # Make the request + client.delete_tool(request=request) + + Args: + request (Union[google.cloud.dialogflow_v2.types.DeleteToolRequest, dict]): + The request object. Request of DeleteTool. + name (str): + Required. The tool resource name to delete. Format: + ``projects//locations//tools/`` + + 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, tool.DeleteToolRequest): + request = tool.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 update_tool( + self, + request: Optional[Union[gcd_tool.UpdateToolRequest, dict]] = None, + *, + tool: Optional[gcd_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]]] = (), + ) -> gcd_tool.Tool: + r"""Updates a 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 dialogflow_v2 + + def sample_update_tool(): + # Create a client + client = dialogflow_v2.ToolsClient() + + # Initialize request argument(s) + tool = dialogflow_v2.Tool() + tool.extension_spec.name = "name_value" + tool.tool_key = "tool_key_value" + + request = dialogflow_v2.UpdateToolRequest( + tool=tool, + ) + + # Make the request + response = client.update_tool(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.dialogflow_v2.types.UpdateToolRequest, dict]): + The request object. Request of UpdateTool. + tool (google.cloud.dialogflow_v2.types.Tool): + Required. The tool to update. + The name field of tool is to identify + 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. 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.dialogflow_v2.types.Tool: + Represents a tool. + """ + # 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, gcd_tool.UpdateToolRequest): + request = gcd_tool.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 __enter__(self) -> "ToolsClient": + 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 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__ = ("ToolsClient",) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/tools/pagers.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/tools/pagers.py new file mode 100644 index 000000000000..0e44b3d25931 --- /dev/null +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/tools/pagers.py @@ -0,0 +1,197 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.dialogflow_v2.types import tool + + +class ListToolsPager: + """A pager for iterating through ``list_tools`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dialogflow_v2.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.dialogflow_v2.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[..., tool.ListToolsResponse], + request: tool.ListToolsRequest, + response: tool.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.dialogflow_v2.types.ListToolsRequest): + The initial request object. + response (google.cloud.dialogflow_v2.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 = tool.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[tool.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.dialogflow_v2.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.dialogflow_v2.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[tool.ListToolsResponse]], + request: tool.ListToolsRequest, + response: tool.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.dialogflow_v2.types.ListToolsRequest): + The initial request object. + response (google.cloud.dialogflow_v2.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 = tool.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[tool.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) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/tools/transports/README.rst b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/tools/transports/README.rst new file mode 100644 index 000000000000..f7b77e1167bf --- /dev/null +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/tools/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`ToolsTransport` is the ABC for all transports. +- public child `ToolsGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `ToolsGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseToolsRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `ToolsRestTransport` 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-dialogflow/google/cloud/dialogflow_v2/services/tools/transports/__init__.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/tools/transports/__init__.py new file mode 100644 index 000000000000..6cd24e40959c --- /dev/null +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/tools/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 ToolsTransport +from .grpc import ToolsGrpcTransport +from .grpc_asyncio import ToolsGrpcAsyncIOTransport +from .rest import ToolsRestInterceptor, ToolsRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ToolsTransport]] +_transport_registry["grpc"] = ToolsGrpcTransport +_transport_registry["grpc_asyncio"] = ToolsGrpcAsyncIOTransport +_transport_registry["rest"] = ToolsRestTransport + +__all__ = ( + "ToolsTransport", + "ToolsGrpcTransport", + "ToolsGrpcAsyncIOTransport", + "ToolsRestTransport", + "ToolsRestInterceptor", +) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/tools/transports/base.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/tools/transports/base.py new file mode 100644 index 000000000000..883317c67e7b --- /dev/null +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/tools/transports/base.py @@ -0,0 +1,296 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +import google.auth # type: ignore +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 +import google.protobuf +from google.protobuf import empty_pb2 # type: ignore + +from google.cloud.dialogflow_v2 import gapic_version as package_version +from google.cloud.dialogflow_v2.types import tool +from google.cloud.dialogflow_v2.types import tool as gcd_tool + +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 ToolsTransport(abc.ABC): + """Abstract transport class for Tools.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ) + + DEFAULT_HOST: str = "dialogflow.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: 'dialogflow.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. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # 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_kwargs, quota_project_id=quota_project_id + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # 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.create_tool: gapic_v1.method.wrap_method( + self.create_tool, + 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_tools: gapic_v1.method.wrap_method( + self.list_tools, + 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.update_tool: gapic_v1.method.wrap_method( + self.update_tool, + 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.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 create_tool( + self, + ) -> Callable[ + [gcd_tool.CreateToolRequest], Union[gcd_tool.Tool, Awaitable[gcd_tool.Tool]] + ]: + raise NotImplementedError() + + @property + def get_tool( + self, + ) -> Callable[[tool.GetToolRequest], Union[tool.Tool, Awaitable[tool.Tool]]]: + raise NotImplementedError() + + @property + def list_tools( + self, + ) -> Callable[ + [tool.ListToolsRequest], + Union[tool.ListToolsResponse, Awaitable[tool.ListToolsResponse]], + ]: + raise NotImplementedError() + + @property + def delete_tool( + self, + ) -> Callable[ + [tool.DeleteToolRequest], Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]] + ]: + raise NotImplementedError() + + @property + def update_tool( + self, + ) -> Callable[ + [gcd_tool.UpdateToolRequest], Union[gcd_tool.Tool, Awaitable[gcd_tool.Tool]] + ]: + 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 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__ = ("ToolsTransport",) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/tools/transports/grpc.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/tools/transports/grpc.py new file mode 100644 index 000000000000..6696dc84c87c --- /dev/null +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/tools/transports/grpc.py @@ -0,0 +1,547 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, grpc_helpers +import google.auth # type: ignore +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 import empty_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore + +from google.cloud.dialogflow_v2.types import tool +from google.cloud.dialogflow_v2.types import tool as gcd_tool + +from .base import DEFAULT_CLIENT_INFO, ToolsTransport + +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.dialogflow.v2.Tools", + "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.dialogflow.v2.Tools", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class ToolsGrpcTransport(ToolsTransport): + """gRPC backend transport for Tools. + + Tool Service for LLM powered Agent Assist. Tools can be used + to interact with remote APIs (e.g. fetching orders) to retrieve + additional information as input to LLM. + + 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 = "dialogflow.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: 'dialogflow.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 = "dialogflow.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 create_tool(self) -> Callable[[gcd_tool.CreateToolRequest], gcd_tool.Tool]: + r"""Return a callable for the create tool method over gRPC. + + Creates a tool. + + 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.dialogflow.v2.Tools/CreateTool", + request_serializer=gcd_tool.CreateToolRequest.serialize, + response_deserializer=gcd_tool.Tool.deserialize, + ) + return self._stubs["create_tool"] + + @property + def get_tool(self) -> Callable[[tool.GetToolRequest], tool.Tool]: + r"""Return a callable for the get tool method over gRPC. + + Retrieves a 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.dialogflow.v2.Tools/GetTool", + request_serializer=tool.GetToolRequest.serialize, + response_deserializer=tool.Tool.deserialize, + ) + return self._stubs["get_tool"] + + @property + def list_tools(self) -> Callable[[tool.ListToolsRequest], tool.ListToolsResponse]: + r"""Return a callable for the list tools method over gRPC. + + Lists tools. + + 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.dialogflow.v2.Tools/ListTools", + request_serializer=tool.ListToolsRequest.serialize, + response_deserializer=tool.ListToolsResponse.deserialize, + ) + return self._stubs["list_tools"] + + @property + def delete_tool(self) -> Callable[[tool.DeleteToolRequest], empty_pb2.Empty]: + r"""Return a callable for the delete tool method over gRPC. + + Deletes a 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.dialogflow.v2.Tools/DeleteTool", + request_serializer=tool.DeleteToolRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_tool"] + + @property + def update_tool(self) -> Callable[[gcd_tool.UpdateToolRequest], gcd_tool.Tool]: + r"""Return a callable for the update tool method over gRPC. + + Updates a 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.dialogflow.v2.Tools/UpdateTool", + request_serializer=gcd_tool.UpdateToolRequest.serialize, + response_deserializer=gcd_tool.Tool.deserialize, + ) + return self._stubs["update_tool"] + + def close(self): + self._logged_channel.close() + + @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__ = ("ToolsGrpcTransport",) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/tools/transports/grpc_asyncio.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/tools/transports/grpc_asyncio.py new file mode 100644 index 000000000000..3f53cb4088ed --- /dev/null +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/tools/transports/grpc_asyncio.py @@ -0,0 +1,623 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +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 import empty_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +import google.protobuf.message +import grpc # type: ignore +from grpc.experimental import aio # type: ignore +import proto # type: ignore + +from google.cloud.dialogflow_v2.types import tool +from google.cloud.dialogflow_v2.types import tool as gcd_tool + +from .base import DEFAULT_CLIENT_INFO, ToolsTransport +from .grpc import ToolsGrpcTransport + +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.dialogflow.v2.Tools", + "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.dialogflow.v2.Tools", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class ToolsGrpcAsyncIOTransport(ToolsTransport): + """gRPC AsyncIO backend transport for Tools. + + Tool Service for LLM powered Agent Assist. Tools can be used + to interact with remote APIs (e.g. fetching orders) to retrieve + additional information as input to LLM. + + 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 = "dialogflow.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 = "dialogflow.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: 'dialogflow.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 create_tool( + self, + ) -> Callable[[gcd_tool.CreateToolRequest], Awaitable[gcd_tool.Tool]]: + r"""Return a callable for the create tool method over gRPC. + + Creates a tool. + + 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.dialogflow.v2.Tools/CreateTool", + request_serializer=gcd_tool.CreateToolRequest.serialize, + response_deserializer=gcd_tool.Tool.deserialize, + ) + return self._stubs["create_tool"] + + @property + def get_tool(self) -> Callable[[tool.GetToolRequest], Awaitable[tool.Tool]]: + r"""Return a callable for the get tool method over gRPC. + + Retrieves a 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.dialogflow.v2.Tools/GetTool", + request_serializer=tool.GetToolRequest.serialize, + response_deserializer=tool.Tool.deserialize, + ) + return self._stubs["get_tool"] + + @property + def list_tools( + self, + ) -> Callable[[tool.ListToolsRequest], Awaitable[tool.ListToolsResponse]]: + r"""Return a callable for the list tools method over gRPC. + + Lists tools. + + 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.dialogflow.v2.Tools/ListTools", + request_serializer=tool.ListToolsRequest.serialize, + response_deserializer=tool.ListToolsResponse.deserialize, + ) + return self._stubs["list_tools"] + + @property + def delete_tool( + self, + ) -> Callable[[tool.DeleteToolRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete tool method over gRPC. + + Deletes a 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.dialogflow.v2.Tools/DeleteTool", + request_serializer=tool.DeleteToolRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_tool"] + + @property + def update_tool( + self, + ) -> Callable[[gcd_tool.UpdateToolRequest], Awaitable[gcd_tool.Tool]]: + r"""Return a callable for the update tool method over gRPC. + + Updates a 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.dialogflow.v2.Tools/UpdateTool", + request_serializer=gcd_tool.UpdateToolRequest.serialize, + response_deserializer=gcd_tool.Tool.deserialize, + ) + return self._stubs["update_tool"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.create_tool: self._wrap_method( + self.create_tool, + 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_tools: self._wrap_method( + self.list_tools, + default_timeout=None, + client_info=client_info, + ), + self.delete_tool: self._wrap_method( + self.delete_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.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.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 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__ = ("ToolsGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/tools/transports/rest.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/tools/transports/rest.py new file mode 100644 index 000000000000..cf15dedcdaaf --- /dev/null +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/tools/transports/rest.py @@ -0,0 +1,1928 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +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 +import google.protobuf +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.dialogflow_v2.types import tool +from google.cloud.dialogflow_v2.types import tool as gcd_tool + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseToolsRestTransport + +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 ToolsRestInterceptor: + """Interceptor for Tools. + + 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 ToolsRestTransport. + + .. code-block:: python + class MyCustomToolsInterceptor(ToolsRestInterceptor): + 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_delete_tool(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + 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_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_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 + + transport = ToolsRestTransport(interceptor=MyCustomToolsInterceptor()) + client = ToolsClient(transport=transport) + + + """ + + def pre_create_tool( + self, + request: gcd_tool.CreateToolRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gcd_tool.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 Tools server. + """ + return request, metadata + + def post_create_tool(self, response: gcd_tool.Tool) -> gcd_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 Tools 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: gcd_tool.Tool, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[gcd_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 Tools 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_delete_tool( + self, + request: tool.DeleteToolRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[tool.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 Tools server. + """ + return request, metadata + + def pre_get_tool( + self, + request: tool.GetToolRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[tool.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 Tools 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 Tools 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 Tools 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_list_tools( + self, + request: tool.ListToolsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[tool.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 Tools server. + """ + return request, metadata + + def post_list_tools( + self, response: tool.ListToolsResponse + ) -> tool.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 Tools 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: tool.ListToolsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[tool.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 Tools 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_update_tool( + self, + request: gcd_tool.UpdateToolRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gcd_tool.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 Tools server. + """ + return request, metadata + + def post_update_tool(self, response: gcd_tool.Tool) -> gcd_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 Tools 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: gcd_tool.Tool, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[gcd_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 Tools 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_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 Tools 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 Tools 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 Tools 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 Tools 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 Tools 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 Tools 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 Tools 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 Tools 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 Tools 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 Tools server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class ToolsRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ToolsRestInterceptor + + +class ToolsRestTransport(_BaseToolsRestTransport): + """REST backend synchronous transport for Tools. + + Tool Service for LLM powered Agent Assist. Tools can be used + to interact with remote APIs (e.g. fetching orders) to retrieve + additional information as input to LLM. + + 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 = "dialogflow.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[ToolsRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'dialogflow.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 ToolsRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateTool(_BaseToolsRestTransport._BaseCreateTool, ToolsRestStub): + def __hash__(self): + return hash("ToolsRestTransport.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: gcd_tool.CreateToolRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcd_tool.Tool: + r"""Call the create tool method over HTTP. + + Args: + request (~.gcd_tool.CreateToolRequest): + The request object. Request message of 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: + ~.gcd_tool.Tool: + Represents a tool. + """ + + http_options = _BaseToolsRestTransport._BaseCreateTool._get_http_options() + + request, metadata = self._interceptor.pre_create_tool(request, metadata) + transcoded_request = ( + _BaseToolsRestTransport._BaseCreateTool._get_transcoded_request( + http_options, request + ) + ) + + body = _BaseToolsRestTransport._BaseCreateTool._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BaseToolsRestTransport._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.dialogflow_v2.ToolsClient.CreateTool", + extra={ + "serviceName": "google.cloud.dialogflow.v2.Tools", + "rpcName": "CreateTool", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ToolsRestTransport._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 = gcd_tool.Tool() + pb_resp = gcd_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 = gcd_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.dialogflow_v2.ToolsClient.create_tool", + extra={ + "serviceName": "google.cloud.dialogflow.v2.Tools", + "rpcName": "CreateTool", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteTool(_BaseToolsRestTransport._BaseDeleteTool, ToolsRestStub): + def __hash__(self): + return hash("ToolsRestTransport.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: tool.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 (~.tool.DeleteToolRequest): + The request object. Request of 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 = _BaseToolsRestTransport._BaseDeleteTool._get_http_options() + + request, metadata = self._interceptor.pre_delete_tool(request, metadata) + transcoded_request = ( + _BaseToolsRestTransport._BaseDeleteTool._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseToolsRestTransport._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 = 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.dialogflow_v2.ToolsClient.DeleteTool", + extra={ + "serviceName": "google.cloud.dialogflow.v2.Tools", + "rpcName": "DeleteTool", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ToolsRestTransport._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 _GetTool(_BaseToolsRestTransport._BaseGetTool, ToolsRestStub): + def __hash__(self): + return hash("ToolsRestTransport.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: tool.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 (~.tool.GetToolRequest): + The request object. Request message of 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: + Represents a tool. + """ + + http_options = _BaseToolsRestTransport._BaseGetTool._get_http_options() + + request, metadata = self._interceptor.pre_get_tool(request, metadata) + transcoded_request = ( + _BaseToolsRestTransport._BaseGetTool._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = _BaseToolsRestTransport._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.dialogflow_v2.ToolsClient.GetTool", + extra={ + "serviceName": "google.cloud.dialogflow.v2.Tools", + "rpcName": "GetTool", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ToolsRestTransport._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.dialogflow_v2.ToolsClient.get_tool", + extra={ + "serviceName": "google.cloud.dialogflow.v2.Tools", + "rpcName": "GetTool", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListTools(_BaseToolsRestTransport._BaseListTools, ToolsRestStub): + def __hash__(self): + return hash("ToolsRestTransport.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: tool.ListToolsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> tool.ListToolsResponse: + r"""Call the list tools method over HTTP. + + Args: + request (~.tool.ListToolsRequest): + The request object. Request message of 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: + ~.tool.ListToolsResponse: + Response of ListTools. + """ + + http_options = _BaseToolsRestTransport._BaseListTools._get_http_options() + + request, metadata = self._interceptor.pre_list_tools(request, metadata) + transcoded_request = ( + _BaseToolsRestTransport._BaseListTools._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseToolsRestTransport._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.dialogflow_v2.ToolsClient.ListTools", + extra={ + "serviceName": "google.cloud.dialogflow.v2.Tools", + "rpcName": "ListTools", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ToolsRestTransport._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 = tool.ListToolsResponse() + pb_resp = tool.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 = tool.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.dialogflow_v2.ToolsClient.list_tools", + extra={ + "serviceName": "google.cloud.dialogflow.v2.Tools", + "rpcName": "ListTools", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateTool(_BaseToolsRestTransport._BaseUpdateTool, ToolsRestStub): + def __hash__(self): + return hash("ToolsRestTransport.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: gcd_tool.UpdateToolRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcd_tool.Tool: + r"""Call the update tool method over HTTP. + + Args: + request (~.gcd_tool.UpdateToolRequest): + The request object. Request of 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: + ~.gcd_tool.Tool: + Represents a tool. + """ + + http_options = _BaseToolsRestTransport._BaseUpdateTool._get_http_options() + + request, metadata = self._interceptor.pre_update_tool(request, metadata) + transcoded_request = ( + _BaseToolsRestTransport._BaseUpdateTool._get_transcoded_request( + http_options, request + ) + ) + + body = _BaseToolsRestTransport._BaseUpdateTool._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BaseToolsRestTransport._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.dialogflow_v2.ToolsClient.UpdateTool", + extra={ + "serviceName": "google.cloud.dialogflow.v2.Tools", + "rpcName": "UpdateTool", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ToolsRestTransport._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 = gcd_tool.Tool() + pb_resp = gcd_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 = gcd_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.dialogflow_v2.ToolsClient.update_tool", + extra={ + "serviceName": "google.cloud.dialogflow.v2.Tools", + "rpcName": "UpdateTool", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_tool(self) -> Callable[[gcd_tool.CreateToolRequest], gcd_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 delete_tool(self) -> Callable[[tool.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 get_tool(self) -> Callable[[tool.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 list_tools(self) -> Callable[[tool.ListToolsRequest], tool.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 update_tool(self) -> Callable[[gcd_tool.UpdateToolRequest], gcd_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 get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation(_BaseToolsRestTransport._BaseGetLocation, ToolsRestStub): + def __hash__(self): + return hash("ToolsRestTransport.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 = _BaseToolsRestTransport._BaseGetLocation._get_http_options() + + request, metadata = self._interceptor.pre_get_location(request, metadata) + transcoded_request = ( + _BaseToolsRestTransport._BaseGetLocation._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseToolsRestTransport._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.dialogflow_v2.ToolsClient.GetLocation", + extra={ + "serviceName": "google.cloud.dialogflow.v2.Tools", + "rpcName": "GetLocation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ToolsRestTransport._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.dialogflow_v2.ToolsAsyncClient.GetLocation", + extra={ + "serviceName": "google.cloud.dialogflow.v2.Tools", + "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(_BaseToolsRestTransport._BaseListLocations, ToolsRestStub): + def __hash__(self): + return hash("ToolsRestTransport.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 = ( + _BaseToolsRestTransport._BaseListLocations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_locations(request, metadata) + transcoded_request = ( + _BaseToolsRestTransport._BaseListLocations._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseToolsRestTransport._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.dialogflow_v2.ToolsClient.ListLocations", + extra={ + "serviceName": "google.cloud.dialogflow.v2.Tools", + "rpcName": "ListLocations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ToolsRestTransport._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.dialogflow_v2.ToolsAsyncClient.ListLocations", + extra={ + "serviceName": "google.cloud.dialogflow.v2.Tools", + "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(_BaseToolsRestTransport._BaseCancelOperation, ToolsRestStub): + def __hash__(self): + return hash("ToolsRestTransport.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), + ) + 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 = ( + _BaseToolsRestTransport._BaseCancelOperation._get_http_options() + ) + + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + transcoded_request = ( + _BaseToolsRestTransport._BaseCancelOperation._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseToolsRestTransport._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.dialogflow_v2.ToolsClient.CancelOperation", + extra={ + "serviceName": "google.cloud.dialogflow.v2.Tools", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ToolsRestTransport._CancelOperation._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_cancel_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(_BaseToolsRestTransport._BaseGetOperation, ToolsRestStub): + def __hash__(self): + return hash("ToolsRestTransport.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 = _BaseToolsRestTransport._BaseGetOperation._get_http_options() + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = ( + _BaseToolsRestTransport._BaseGetOperation._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseToolsRestTransport._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.dialogflow_v2.ToolsClient.GetOperation", + extra={ + "serviceName": "google.cloud.dialogflow.v2.Tools", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ToolsRestTransport._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.dialogflow_v2.ToolsAsyncClient.GetOperation", + extra={ + "serviceName": "google.cloud.dialogflow.v2.Tools", + "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(_BaseToolsRestTransport._BaseListOperations, ToolsRestStub): + def __hash__(self): + return hash("ToolsRestTransport.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 = ( + _BaseToolsRestTransport._BaseListOperations._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request = ( + _BaseToolsRestTransport._BaseListOperations._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseToolsRestTransport._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.dialogflow_v2.ToolsClient.ListOperations", + extra={ + "serviceName": "google.cloud.dialogflow.v2.Tools", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ToolsRestTransport._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.dialogflow_v2.ToolsAsyncClient.ListOperations", + extra={ + "serviceName": "google.cloud.dialogflow.v2.Tools", + "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__ = ("ToolsRestTransport",) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/tools/transports/rest_base.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/tools/transports/rest_base.py new file mode 100644 index 000000000000..c032ba8fc4d9 --- /dev/null +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/services/tools/transports/rest_base.py @@ -0,0 +1,487 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 empty_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.dialogflow_v2.types import tool +from google.cloud.dialogflow_v2.types import tool as gcd_tool + +from .base import DEFAULT_CLIENT_INFO, ToolsTransport + + +class _BaseToolsRestTransport(ToolsTransport): + """Base REST backend transport for Tools. + + 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 = "dialogflow.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: 'dialogflow.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 _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": "/v2/{parent=projects/*/locations/*}/tools", + "body": "tool", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcd_tool.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( + _BaseToolsRestTransport._BaseCreateTool._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": "/v2/{name=projects/*/locations/*/tools/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = tool.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( + _BaseToolsRestTransport._BaseDeleteTool._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": "/v2/{name=projects/*/locations/*/tools/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = tool.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( + _BaseToolsRestTransport._BaseGetTool._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": "/v2/{parent=projects/*/locations/*}/tools", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = tool.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( + _BaseToolsRestTransport._BaseListTools._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": "/v2/{tool.name=projects/*/locations/*/tools/*}", + "body": "tool", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gcd_tool.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( + _BaseToolsRestTransport._BaseUpdateTool._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": "/v2/{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": "/v2/{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": "/v2/{name=projects/*/operations/*}:cancel", + }, + { + "method": "post", + "uri": "/v2/{name=projects/*/locations/*/operations/*}:cancel", + }, + ] + 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": "/v2/{name=projects/*/operations/*}", + }, + { + "method": "get", + "uri": "/v2/{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": "/v2/{name=projects/*}/operations", + }, + { + "method": "get", + "uri": "/v2/{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__ = ("_BaseToolsRestTransport",) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/__init__.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/__init__.py index b85df86f71cf..8455a2beab80 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/__init__.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/__init__.py @@ -27,6 +27,7 @@ SetAgentRequest, TrainAgentRequest, ) +from .agent_coaching_instruction import AgentCoachingInstruction from .answer_record import ( AgentAssistantFeedback, AgentAssistantRecord, @@ -38,6 +39,7 @@ ) from .audio_config import ( AudioEncoding, + CustomPronunciationParams, InputAudioConfig, OutputAudioConfig, OutputAudioEncoding, @@ -198,6 +200,8 @@ from .fulfillment import Fulfillment, GetFulfillmentRequest, UpdateFulfillmentRequest from .gcs import GcsDestination, GcsSources from .generator import ( + AgentCoachingContext, + AgentCoachingSuggestion, ConversationContext, CreateGeneratorRequest, DeleteGeneratorRequest, @@ -211,6 +215,8 @@ ListGeneratorsRequest, ListGeneratorsResponse, MessageEntry, + RaiSettings, + SuggestionDedupingConfig, SummarizationContext, SummarizationSection, SummarizationSectionList, @@ -218,6 +224,17 @@ TriggerEvent, UpdateGeneratorRequest, ) +from .generator_evaluation import ( + CreateGeneratorEvaluationRequest, + DeleteGeneratorEvaluationRequest, + EvaluationStatus, + GeneratorEvaluation, + GeneratorEvaluationConfig, + GetGeneratorEvaluationRequest, + ListGeneratorEvaluationsRequest, + ListGeneratorEvaluationsResponse, + SummarizationEvaluationMetrics, +) from .human_agent_assistant_event import HumanAgentAssistantEvent from .intent import ( BatchDeleteIntentsRequest, @@ -242,6 +259,7 @@ ListKnowledgeBasesResponse, UpdateKnowledgeBaseRequest, ) +from .operations import GeneratorEvaluationOperationMetadata from .participant import ( AnalyzeContentRequest, AnalyzeContentResponse, @@ -305,6 +323,26 @@ SessionEntityType, UpdateSessionEntityTypeRequest, ) +from .sip_trunk import ( + Connection, + CreateSipTrunkRequest, + DeleteSipTrunkRequest, + GetSipTrunkRequest, + ListSipTrunksRequest, + ListSipTrunksResponse, + SipTrunk, + UpdateSipTrunkRequest, +) +from .tool import ( + CreateToolRequest, + DeleteToolRequest, + GetToolRequest, + ListToolsRequest, + ListToolsResponse, + Tool, + UpdateToolRequest, +) +from .tool_call import ToolCall, ToolCallResult from .validation_result import ValidationError, ValidationResult from .version import ( CreateVersionRequest, @@ -330,6 +368,7 @@ "SearchAgentsResponse", "SetAgentRequest", "TrainAgentRequest", + "AgentCoachingInstruction", "AgentAssistantFeedback", "AgentAssistantRecord", "AnswerFeedback", @@ -337,6 +376,7 @@ "ListAnswerRecordsRequest", "ListAnswerRecordsResponse", "UpdateAnswerRecordRequest", + "CustomPronunciationParams", "InputAudioConfig", "OutputAudioConfig", "SpeechContext", @@ -481,6 +521,8 @@ "UpdateFulfillmentRequest", "GcsDestination", "GcsSources", + "AgentCoachingContext", + "AgentCoachingSuggestion", "ConversationContext", "CreateGeneratorRequest", "DeleteGeneratorRequest", @@ -494,12 +536,23 @@ "ListGeneratorsRequest", "ListGeneratorsResponse", "MessageEntry", + "RaiSettings", + "SuggestionDedupingConfig", "SummarizationContext", "SummarizationSection", "SummarizationSectionList", "SummarySuggestion", "UpdateGeneratorRequest", "TriggerEvent", + "CreateGeneratorEvaluationRequest", + "DeleteGeneratorEvaluationRequest", + "EvaluationStatus", + "GeneratorEvaluation", + "GeneratorEvaluationConfig", + "GetGeneratorEvaluationRequest", + "ListGeneratorEvaluationsRequest", + "ListGeneratorEvaluationsResponse", + "SummarizationEvaluationMetrics", "HumanAgentAssistantEvent", "BatchDeleteIntentsRequest", "BatchUpdateIntentsRequest", @@ -520,6 +573,7 @@ "ListKnowledgeBasesRequest", "ListKnowledgeBasesResponse", "UpdateKnowledgeBaseRequest", + "GeneratorEvaluationOperationMetadata", "AnalyzeContentRequest", "AnalyzeContentResponse", "AnnotatedMessagePart", @@ -577,6 +631,23 @@ "ListSessionEntityTypesResponse", "SessionEntityType", "UpdateSessionEntityTypeRequest", + "Connection", + "CreateSipTrunkRequest", + "DeleteSipTrunkRequest", + "GetSipTrunkRequest", + "ListSipTrunksRequest", + "ListSipTrunksResponse", + "SipTrunk", + "UpdateSipTrunkRequest", + "CreateToolRequest", + "DeleteToolRequest", + "GetToolRequest", + "ListToolsRequest", + "ListToolsResponse", + "Tool", + "UpdateToolRequest", + "ToolCall", + "ToolCallResult", "ValidationError", "ValidationResult", "CreateVersionRequest", diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/agent_coaching_instruction.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/agent_coaching_instruction.py new file mode 100644 index 000000000000..d9bbe4178e23 --- /dev/null +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/agent_coaching_instruction.py @@ -0,0 +1,166 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.dialogflow.v2", + manifest={ + "AgentCoachingInstruction", + }, +) + + +class AgentCoachingInstruction(proto.Message): + r"""Agent Coaching instructions that customer can configure. + + Attributes: + display_name (str): + Optional. Display name for the instruction. + display_details (str): + Optional. The detailed description of this + instruction. + condition (str): + Optional. The condition of the instruction. + For example, "the customer wants to cancel an + order". If the users want the instruction to be + triggered unconditionally, the condition can be + empty. + agent_action (str): + Optional. The action that human agent should take. For + example, "apologize for the slow shipping". If the users + only want to use agent coaching for intent detection, + agent_action can be empty + system_action (str): + Optional. The action that system should take. For example, + "call GetOrderTime with order_number={order number provided + by the customer}". If the users don't have plugins or don't + want to trigger plugins, the system_action can be empty + duplicate_check_result (google.cloud.dialogflow_v2.types.AgentCoachingInstruction.DuplicateCheckResult): + Output only. Duplication check for the + AgentCoachingInstruction. + triggering_event (google.cloud.dialogflow_v2.types.AgentCoachingInstruction.TriggerEvent): + Optional. The event that should trigger this instruction. If + UNSPECIFIED, the instruction triggering will be same as the + generator's trigger_event. + """ + + class TriggerEvent(proto.Enum): + r"""The event that should trigger this instruction. + + Values: + TRIGGER_EVENT_UNSPECIFIED (0): + Default value for TriggerEvent. + END_OF_UTTERANCE (1): + Triggers when each chat message or voice + utterance ends. + MANUAL_CALL (2): + Triggers on the conversation manually by API + calls. + CUSTOMER_MESSAGE (3): + Triggers after each customer message. + AGENT_MESSAGE (4): + Triggers after each agent message. + TOOL_CALL_COMPLETION (5): + Triggers on tool call completion. + """ + TRIGGER_EVENT_UNSPECIFIED = 0 + END_OF_UTTERANCE = 1 + MANUAL_CALL = 2 + CUSTOMER_MESSAGE = 3 + AGENT_MESSAGE = 4 + TOOL_CALL_COMPLETION = 5 + + class DuplicateCheckResult(proto.Message): + r"""Duplication check for the suggestion. + + Attributes: + duplicate_suggestions (MutableSequence[google.cloud.dialogflow_v2.types.AgentCoachingInstruction.DuplicateCheckResult.DuplicateSuggestion]): + Output only. The duplicate suggestions. + """ + + class DuplicateSuggestion(proto.Message): + r"""The duplicate suggestion details. + + Attributes: + answer_record (str): + Output only. The answer record id of the past + duplicate suggestion. + suggestion_index (int): + Output only. The index of the duplicate + suggestion in the past suggestion list. + similarity_score (float): + Output only. The similarity score of between + the past and current suggestion. + """ + + answer_record: str = proto.Field( + proto.STRING, + number=1, + ) + suggestion_index: int = proto.Field( + proto.INT32, + number=3, + ) + similarity_score: float = proto.Field( + proto.FLOAT, + number=4, + ) + + duplicate_suggestions: MutableSequence[ + "AgentCoachingInstruction.DuplicateCheckResult.DuplicateSuggestion" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="AgentCoachingInstruction.DuplicateCheckResult.DuplicateSuggestion", + ) + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + display_details: str = proto.Field( + proto.STRING, + number=2, + ) + condition: str = proto.Field( + proto.STRING, + number=3, + ) + agent_action: str = proto.Field( + proto.STRING, + number=4, + ) + system_action: str = proto.Field( + proto.STRING, + number=5, + ) + duplicate_check_result: DuplicateCheckResult = proto.Field( + proto.MESSAGE, + number=8, + message=DuplicateCheckResult, + ) + triggering_event: TriggerEvent = proto.Field( + proto.ENUM, + number=10, + enum=TriggerEvent, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/answer_record.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/answer_record.py index 259dfa22e20b..bf6345de22aa 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/answer_record.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/answer_record.py @@ -21,7 +21,7 @@ from google.protobuf import timestamp_pb2 # type: ignore import proto # type: ignore -from google.cloud.dialogflow_v2.types import participant +from google.cloud.dialogflow_v2.types import generator, participant __protobuf__ = proto.module( package="google.cloud.dialogflow.v2", @@ -529,6 +529,10 @@ class AgentAssistantRecord(proto.Message): dialogflow_assist_answer (google.cloud.dialogflow_v2.types.DialogflowAssistAnswer): Output only. Dialogflow assist answer. + This field is a member of `oneof`_ ``answer``. + generator_suggestion (google.cloud.dialogflow_v2.types.GeneratorSuggestion): + Output only. The generator suggestion. + This field is a member of `oneof`_ ``answer``. """ @@ -550,6 +554,12 @@ class AgentAssistantRecord(proto.Message): oneof="answer", message=participant.DialogflowAssistAnswer, ) + generator_suggestion: generator.GeneratorSuggestion = proto.Field( + proto.MESSAGE, + number=8, + oneof="answer", + message=generator.GeneratorSuggestion, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/audio_config.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/audio_config.py index 4c4365191e0c..e9e3836f66fa 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/audio_config.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/audio_config.py @@ -33,6 +33,7 @@ "InputAudioConfig", "VoiceSelectionParams", "SynthesizeSpeechConfig", + "CustomPronunciationParams", "OutputAudioConfig", "TelephonyDtmfEvents", "SpeechToTextConfig", @@ -386,7 +387,9 @@ class InputAudioConfig(proto.Message): Support `__ for a list of the currently supported language codes. Note that queries in the same session do not necessarily need to - specify the same language. + specify the same language. If not set, the language is + inferred from the + [ConversationProfile.stt_config][google.cloud.dialogflow.v2.ConversationProfile.stt_config]. enable_word_info (bool): If ``true``, Dialogflow returns [SpeechWordInfo][google.cloud.dialogflow.v2.SpeechWordInfo] @@ -576,6 +579,9 @@ class SynthesizeSpeechConfig(proto.Message): voice (google.cloud.dialogflow_v2.types.VoiceSelectionParams): Optional. The desired voice of the synthesized audio. + pronunciations (MutableSequence[google.cloud.dialogflow_v2.types.CustomPronunciationParams]): + Optional. The custom pronunciations for the + synthesized audio. """ speaking_rate: float = proto.Field( @@ -599,6 +605,59 @@ class SynthesizeSpeechConfig(proto.Message): number=4, message="VoiceSelectionParams", ) + pronunciations: MutableSequence["CustomPronunciationParams"] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message="CustomPronunciationParams", + ) + + +class CustomPronunciationParams(proto.Message): + r"""Pronunciation customization for a phrase. + + Attributes: + phrase (str): + The phrase to which the customization is + applied. The phrase can be multiple words, such + as proper nouns, but shouldn't span the length + of the sentence. + phonetic_encoding (google.cloud.dialogflow_v2.types.CustomPronunciationParams.PhoneticEncoding): + The phonetic encoding of the phrase. + pronunciation (str): + The pronunciation of the phrase. This must be + in the phonetic encoding specified above. + """ + + class PhoneticEncoding(proto.Enum): + r"""The phonetic encoding of the phrase. + + Values: + PHONETIC_ENCODING_UNSPECIFIED (0): + Not specified. + PHONETIC_ENCODING_IPA (1): + IPA, such as apple -> ˈæpəl. + https://en.wikipedia.org/wiki/International_Phonetic_Alphabet + PHONETIC_ENCODING_X_SAMPA (2): + X-SAMPA, such as apple -> "{p@l". + https://en.wikipedia.org/wiki/X-SAMPA + """ + PHONETIC_ENCODING_UNSPECIFIED = 0 + PHONETIC_ENCODING_IPA = 1 + PHONETIC_ENCODING_X_SAMPA = 2 + + phrase: str = proto.Field( + proto.STRING, + number=1, + ) + phonetic_encoding: PhoneticEncoding = proto.Field( + proto.ENUM, + number=2, + enum=PhoneticEncoding, + ) + pronunciation: str = proto.Field( + proto.STRING, + number=3, + ) class OutputAudioConfig(proto.Message): @@ -711,7 +770,10 @@ class SpeechToTextConfig(proto.Message): Support `__ for a list of the currently supported language codes. Note that queries in the same session do not necessarily need to - specify the same language. + specify the same language. If not specified, the default + language configured at + [ConversationProfile][google.cloud.dialogflow.v2.ConversationProfile] + is used. enable_word_info (bool): If ``true``, Dialogflow returns [SpeechWordInfo][google.cloud.dialogflow.v2.SpeechWordInfo] diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/conversation.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/conversation.py index e4636ac95aca..cee71aae243d 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/conversation.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/conversation.py @@ -156,7 +156,7 @@ class TelephonyConnectionInfo(proto.Message): this call in E.164 format. sdp (str): Optional. SDP of the call. It's initially the - SDP answer to the endpoint, but maybe later + SDP answer to the incoming call, but maybe later updated for the purpose of making the link active, etc. sip_headers (MutableSequence[google.cloud.dialogflow_v2.types.Conversation.TelephonyConnectionInfo.SipHeader]): @@ -277,6 +277,11 @@ class ContextContent(proto.Message): Output only. The time when this information was incorporated into the relevant context reference. + answer_record (str): + If the context content was generated from a tool call, + specify the answer record associated with the tool call. + Format: + ``projects//locations//answerRecords/``. """ class ContentFormat(proto.Enum): @@ -308,6 +313,10 @@ class ContentFormat(proto.Enum): number=3, message=timestamp_pb2.Timestamp, ) + answer_record: str = proto.Field( + proto.STRING, + number=4, + ) context_contents: MutableSequence[ "Conversation.ContextReference.ContextContent" @@ -981,6 +990,15 @@ class GenerateStatelessSuggestionRequest(proto.Message): Optional. A list of trigger events. Generator will be triggered only if it's trigger event is included here. + security_settings (str): + Optional. Name of the CX SecuritySettings which is used to + redact generated response. If this field is empty, try to + fetch v2 security_settings, which is a project level + setting. If this field is empty and no v2 security_settings + set up in this project, no redaction will be done. + + Format: + ``projects//locations//securitySettings/``. """ parent: str = proto.Field( @@ -1016,6 +1034,10 @@ class GenerateStatelessSuggestionRequest(proto.Message): number=6, enum=gcd_generator.TriggerEvent, ) + security_settings: str = proto.Field( + proto.STRING, + number=8, + ) class GenerateStatelessSuggestionResponse(proto.Message): diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/conversation_event.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/conversation_event.py index ecac2e8c2f13..faba94f46e53 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/conversation_event.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/conversation_event.py @@ -75,7 +75,9 @@ class Type(proto.Enum): CONVERSATION_FINISHED (2): An existing conversation has closed. This is fired when a telephone call is terminated, or a - conversation is closed via the API. + conversation is closed via the API. The event is + fired for every CompleteConversation call, even + if the conversation is already closed. HUMAN_INTERVENTION_NEEDED (3): An existing conversation has received notification from Dialogflow that human diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/conversation_model.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/conversation_model.py index 5b54c4856a4d..6a25c639508c 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/conversation_model.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/conversation_model.py @@ -736,6 +736,8 @@ class CreateConversationModelOperationMetadata(proto.Message): Timestamp when the request to create conversation model is submitted. The time is measured on server side. + done_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the operation finished. """ class State(proto.Enum): @@ -782,6 +784,11 @@ class State(proto.Enum): number=3, message=timestamp_pb2.Timestamp, ) + done_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) class DeployConversationModelOperationMetadata(proto.Message): @@ -797,6 +804,8 @@ class DeployConversationModelOperationMetadata(proto.Message): Timestamp when request to deploy conversation model was submitted. The time is measured on server side. + done_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the operation finished. """ conversation_model: str = proto.Field( @@ -808,6 +817,11 @@ class DeployConversationModelOperationMetadata(proto.Message): number=3, message=timestamp_pb2.Timestamp, ) + done_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) class UndeployConversationModelOperationMetadata(proto.Message): @@ -823,6 +837,8 @@ class UndeployConversationModelOperationMetadata(proto.Message): Timestamp when the request to undeploy conversation model was submitted. The time is measured on server side. + done_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the operation finished. """ conversation_model: str = proto.Field( @@ -834,6 +850,11 @@ class UndeployConversationModelOperationMetadata(proto.Message): number=3, message=timestamp_pb2.Timestamp, ) + done_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) class DeleteConversationModelOperationMetadata(proto.Message): @@ -849,6 +870,8 @@ class DeleteConversationModelOperationMetadata(proto.Message): Timestamp when delete conversation model request was created. The time is measured on server side. + done_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the operation finished. """ conversation_model: str = proto.Field( @@ -860,6 +883,11 @@ class DeleteConversationModelOperationMetadata(proto.Message): number=3, message=timestamp_pb2.Timestamp, ) + done_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) class CreateConversationModelEvaluationOperationMetadata(proto.Message): diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/conversation_profile.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/conversation_profile.py index 8084dd6b5374..b1f5d0aa9621 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/conversation_profile.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/conversation_profile.py @@ -22,7 +22,7 @@ from google.protobuf import timestamp_pb2 # type: ignore import proto # type: ignore -from google.cloud.dialogflow_v2.types import audio_config, participant +from google.cloud.dialogflow_v2.types import audio_config, generator, participant __protobuf__ = proto.module( package="google.cloud.dialogflow.v2", @@ -458,6 +458,20 @@ class SuggestionFeatureConfig(proto.Message): enable_query_suggestion_only (bool): Optional. Enable query suggestion only. Supported features: KNOWLEDGE_ASSIST + enable_response_debug_info (bool): + Optional. Enable returning detailed reasons for suggestion + results. + + For example, with this field disabled, Knowledge Search + feature returns NotFound error when no answer is found for + the input query. Enabling this field will change the + behavior to return an OK response with detailed information + indicating the lack of results. + + Supported features: KNOWLEDGE_SEARCH, KNOWLEDGE_ASSIST + rai_settings (google.cloud.dialogflow_v2.types.RaiSettings): + Optional. Settings for Responsible AI checks. Supported + features: KNOWLEDGE_ASSIST suggestion_trigger_settings (google.cloud.dialogflow_v2.types.HumanAgentAssistantConfig.SuggestionTriggerSettings): Settings of suggestion trigger. @@ -496,6 +510,15 @@ class SuggestionFeatureConfig(proto.Message): proto.BOOL, number=17, ) + enable_response_debug_info: bool = proto.Field( + proto.BOOL, + number=18, + ) + rai_settings: generator.RaiSettings = proto.Field( + proto.MESSAGE, + number=19, + message=generator.RaiSettings, + ) suggestion_trigger_settings: "HumanAgentAssistantConfig.SuggestionTriggerSettings" = proto.Field( proto.MESSAGE, number=10, @@ -549,6 +572,22 @@ class SuggestionConfig(proto.Message): configured and enable_event_based_suggestion must be set to true to receive the responses from high latency features in Pub/Sub. High latency feature(s): KNOWLEDGE_ASSIST + skip_empty_event_based_suggestion (bool): + Optional. Enable skipping event based + suggestion if the suggestion is empty. + + For example, with this field disabled, Knowledge + Assist feature sends a Pub/Sub message when + there are no suggestions. Enabling this field + will change the behavior to skip the Pub/Sub + message in this situation. + use_unredacted_conversation_data (bool): + Optional. If true, use unredacted transcript data (Supported + features: AI_COACH) and use unredacted ingested context + (Supported features: All Agent Assist features) + enable_async_tool_call (bool): + Optional. If true, enable asynchronous + execution of tools. """ feature_configs: MutableSequence[ @@ -570,6 +609,18 @@ class SuggestionConfig(proto.Message): proto.BOOL, number=5, ) + skip_empty_event_based_suggestion: bool = proto.Field( + proto.BOOL, + number=6, + ) + use_unredacted_conversation_data: bool = proto.Field( + proto.BOOL, + number=8, + ) + enable_async_tool_call: bool = proto.Field( + proto.BOOL, + number=9, + ) class SuggestionQueryConfig(proto.Message): r"""Config for suggestion query. @@ -858,7 +909,7 @@ class ConversationModelConfig(proto.Message): r"""Custom conversation models used in agent assist feature. Supported feature: ARTICLE_SUGGESTION, SMART_COMPOSE, SMART_REPLY, - CONVERSATION_SUMMARIZATION. + CONVERSATION_SUMMARIZATION Attributes: model (str): @@ -867,9 +918,16 @@ class ConversationModelConfig(proto.Message): baseline_model_version (str): Version of current baseline model. It will be ignored if [model][google.cloud.dialogflow.v2.HumanAgentAssistantConfig.ConversationModelConfig.model] - is set. Valid versions are: Article Suggestion baseline - model: - 0.9 - 1.0 (default) Summarization baseline model: - - 1.0 + is set. Valid versions are: + + - Article Suggestion baseline model: + + - 0.9 + - 1.0 (default) + + - Summarization baseline model: + + - 1.0 """ model: str = proto.Field( diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/document.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/document.py index 0ac413e243d7..17b439f7cc30 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/document.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/document.py @@ -655,6 +655,8 @@ class KnowledgeOperationMetadata(proto.Message): as the destination of export. This field is a member of `oneof`_ ``operation_metadata``. + done_time (google.protobuf.timestamp_pb2.Timestamp): + The time when the operation finished. """ class State(proto.Enum): @@ -691,6 +693,11 @@ class State(proto.Enum): oneof="operation_metadata", message="ExportOperationMetadata", ) + done_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/generator.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/generator.py index 2aa8559f4da6..641db6dfba5b 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/generator.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/generator.py @@ -21,6 +21,9 @@ from google.protobuf import timestamp_pb2 # type: ignore import proto # type: ignore +from google.cloud.dialogflow_v2.types import agent_coaching_instruction +from google.cloud.dialogflow_v2.types import tool_call as gcd_tool_call + __protobuf__ = proto.module( package="google.cloud.dialogflow.v2", manifest={ @@ -36,13 +39,17 @@ "SummarizationSectionList", "FewShotExample", "InferenceParameter", + "AgentCoachingContext", "SummarizationSection", "SummarizationContext", "FreeFormContext", "Generator", "FreeFormSuggestion", "SummarySuggestion", + "AgentCoachingSuggestion", "GeneratorSuggestion", + "SuggestionDedupingConfig", + "RaiSettings", }, ) @@ -430,6 +437,45 @@ class InferenceParameter(proto.Message): ) +class AgentCoachingContext(proto.Message): + r"""Agent Coaching context that customer can configure. + + Attributes: + overarching_guidance (str): + Optional. The overarching guidance for the + agent coaching. This should be set only for v1.5 + and later versions. + instructions (MutableSequence[google.cloud.dialogflow_v2.types.AgentCoachingInstruction]): + Optional. Customized instructions for agent + coaching. + version (str): + Optional. Version of the feature. If not set, default to + latest version. Current candidates are ["1.2"]. + output_language_code (str): + Optional. Output language code. + """ + + overarching_guidance: str = proto.Field( + proto.STRING, + number=7, + ) + instructions: MutableSequence[ + agent_coaching_instruction.AgentCoachingInstruction + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=agent_coaching_instruction.AgentCoachingInstruction, + ) + version: str = proto.Field( + proto.STRING, + number=2, + ) + output_language_code: str = proto.Field( + proto.STRING, + number=9, + ) + + class SummarizationSection(proto.Message): r"""Represents the section of summarization. @@ -589,6 +635,10 @@ class Generator(proto.Message): free_form_context (google.cloud.dialogflow_v2.types.FreeFormContext): Input of free from generator to LLM. + This field is a member of `oneof`_ ``context``. + agent_coaching_context (google.cloud.dialogflow_v2.types.AgentCoachingContext): + Input of prebuilt Agent Coaching feature. + This field is a member of `oneof`_ ``context``. summarization_context (google.cloud.dialogflow_v2.types.SummarizationContext): Input of prebuilt Summarization feature. @@ -614,6 +664,14 @@ class Generator(proto.Message): Output only. Creation time of this generator. update_time (google.protobuf.timestamp_pb2.Timestamp): Output only. Update time of this generator. + tools (MutableSequence[str]): + Optional. Resource names of the tools that the generator can + choose from. Format: + ``projects//locations//tools/``. + suggestion_deduping_config (google.cloud.dialogflow_v2.types.SuggestionDedupingConfig): + Optional. Configuration for suggestion + deduping. This is only applicable to AI Coach + feature. """ name: str = proto.Field( @@ -630,6 +688,12 @@ class Generator(proto.Message): oneof="context", message="FreeFormContext", ) + agent_coaching_context: "AgentCoachingContext" = proto.Field( + proto.MESSAGE, + number=12, + oneof="context", + message="AgentCoachingContext", + ) summarization_context: "SummarizationContext" = proto.Field( proto.MESSAGE, number=13, @@ -661,6 +725,15 @@ class Generator(proto.Message): number=9, message=timestamp_pb2.Timestamp, ) + tools: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=14, + ) + suggestion_deduping_config: "SuggestionDedupingConfig" = proto.Field( + proto.MESSAGE, + number=23, + message="SuggestionDedupingConfig", + ) class FreeFormSuggestion(proto.Message): @@ -711,6 +784,170 @@ class SummarySection(proto.Message): ) +class AgentCoachingSuggestion(proto.Message): + r"""Suggestion for coaching agents. + + Attributes: + applicable_instructions (MutableSequence[google.cloud.dialogflow_v2.types.AgentCoachingInstruction]): + Optional. Instructions applicable based on + the current context. + agent_action_suggestions (MutableSequence[google.cloud.dialogflow_v2.types.AgentCoachingSuggestion.AgentActionSuggestion]): + Optional. Suggested actions for the agent to + take. + sample_responses (MutableSequence[google.cloud.dialogflow_v2.types.AgentCoachingSuggestion.SampleResponse]): + Optional. Sample response for the Agent. + """ + + class Sources(proto.Message): + r"""Sources for the suggestion. + + Attributes: + instruction_indexes (MutableSequence[int]): + Output only. Source instruction indexes for the suggestion. + This is the index of the applicable_instructions field. + """ + + instruction_indexes: MutableSequence[int] = proto.RepeatedField( + proto.INT32, + number=2, + ) + + class DuplicateCheckResult(proto.Message): + r"""Duplication check for the suggestion. + + Attributes: + duplicate_suggestions (MutableSequence[google.cloud.dialogflow_v2.types.AgentCoachingSuggestion.DuplicateCheckResult.DuplicateSuggestion]): + Output only. The duplicate suggestions. + """ + + class DuplicateSuggestion(proto.Message): + r"""The duplicate suggestion details. Keeping answer_record and sources + together as they are identifiers for duplicate suggestions. + + Attributes: + answer_record (str): + Output only. The answer record id of the past + duplicate suggestion. + sources (google.cloud.dialogflow_v2.types.AgentCoachingSuggestion.Sources): + Output only. Sources for the suggestion. + suggestion_index (int): + Output only. The index of the duplicate + suggestion in the past suggestion list. + similarity_score (float): + Output only. The similarity score of between + the past and current suggestion. + """ + + answer_record: str = proto.Field( + proto.STRING, + number=1, + ) + sources: "AgentCoachingSuggestion.Sources" = proto.Field( + proto.MESSAGE, + number=2, + message="AgentCoachingSuggestion.Sources", + ) + suggestion_index: int = proto.Field( + proto.INT32, + number=3, + ) + similarity_score: float = proto.Field( + proto.FLOAT, + number=4, + ) + + duplicate_suggestions: MutableSequence[ + "AgentCoachingSuggestion.DuplicateCheckResult.DuplicateSuggestion" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="AgentCoachingSuggestion.DuplicateCheckResult.DuplicateSuggestion", + ) + + class AgentActionSuggestion(proto.Message): + r"""Actions suggested for the agent. This is based on applicable + instructions. + + Attributes: + agent_action (str): + Optional. The suggested action for the agent. + sources (google.cloud.dialogflow_v2.types.AgentCoachingSuggestion.Sources): + Output only. Sources for the agent action + suggestion. + duplicate_check_result (google.cloud.dialogflow_v2.types.AgentCoachingSuggestion.DuplicateCheckResult): + Output only. Duplicate check result for the + agent action suggestion. + """ + + agent_action: str = proto.Field( + proto.STRING, + number=1, + ) + sources: "AgentCoachingSuggestion.Sources" = proto.Field( + proto.MESSAGE, + number=2, + message="AgentCoachingSuggestion.Sources", + ) + duplicate_check_result: "AgentCoachingSuggestion.DuplicateCheckResult" = ( + proto.Field( + proto.MESSAGE, + number=3, + message="AgentCoachingSuggestion.DuplicateCheckResult", + ) + ) + + class SampleResponse(proto.Message): + r"""Sample response that the agent can use. This could be based + on applicable instructions and ingested data from other systems. + + Attributes: + response_text (str): + Optional. Sample response for Agent in text. + sources (google.cloud.dialogflow_v2.types.AgentCoachingSuggestion.Sources): + Output only. Sources for the Sample Response. + duplicate_check_result (google.cloud.dialogflow_v2.types.AgentCoachingSuggestion.DuplicateCheckResult): + Output only. Duplicate check result for the + sample response. + """ + + response_text: str = proto.Field( + proto.STRING, + number=1, + ) + sources: "AgentCoachingSuggestion.Sources" = proto.Field( + proto.MESSAGE, + number=2, + message="AgentCoachingSuggestion.Sources", + ) + duplicate_check_result: "AgentCoachingSuggestion.DuplicateCheckResult" = ( + proto.Field( + proto.MESSAGE, + number=3, + message="AgentCoachingSuggestion.DuplicateCheckResult", + ) + ) + + applicable_instructions: MutableSequence[ + agent_coaching_instruction.AgentCoachingInstruction + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=agent_coaching_instruction.AgentCoachingInstruction, + ) + agent_action_suggestions: MutableSequence[ + AgentActionSuggestion + ] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=AgentActionSuggestion, + ) + sample_responses: MutableSequence[SampleResponse] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=SampleResponse, + ) + + class GeneratorSuggestion(proto.Message): r"""Suggestion generated using a Generator. @@ -730,8 +967,36 @@ class GeneratorSuggestion(proto.Message): Optional. Suggested summary. This field is a member of `oneof`_ ``suggestion``. + agent_coaching_suggestion (google.cloud.dialogflow_v2.types.AgentCoachingSuggestion): + Optional. Suggestion to coach the agent. + + This field is a member of `oneof`_ ``suggestion``. + tool_call_info (MutableSequence[google.cloud.dialogflow_v2.types.GeneratorSuggestion.ToolCallInfo]): + Optional. List of request and response for + tool calls executed. """ + class ToolCallInfo(proto.Message): + r"""Request and response for a tool call. + + Attributes: + tool_call (google.cloud.dialogflow_v2.types.ToolCall): + Required. Request for a tool call. + tool_call_result (google.cloud.dialogflow_v2.types.ToolCallResult): + Required. Response for a tool call. + """ + + tool_call: gcd_tool_call.ToolCall = proto.Field( + proto.MESSAGE, + number=1, + message=gcd_tool_call.ToolCall, + ) + tool_call_result: gcd_tool_call.ToolCallResult = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_tool_call.ToolCallResult, + ) + free_form_suggestion: "FreeFormSuggestion" = proto.Field( proto.MESSAGE, number=1, @@ -744,6 +1009,125 @@ class GeneratorSuggestion(proto.Message): oneof="suggestion", message="SummarySuggestion", ) + agent_coaching_suggestion: "AgentCoachingSuggestion" = proto.Field( + proto.MESSAGE, + number=3, + oneof="suggestion", + message="AgentCoachingSuggestion", + ) + tool_call_info: MutableSequence[ToolCallInfo] = proto.RepeatedField( + proto.MESSAGE, + number=9, + message=ToolCallInfo, + ) + + +class SuggestionDedupingConfig(proto.Message): + r"""Config for suggestion deduping. NEXT_ID: 3 + + Attributes: + enable_deduping (bool): + Optional. Whether to enable suggestion + deduping. + similarity_threshold (float): + Optional. The threshold for similarity between two + suggestions. Acceptable value is [0.0, 1.0], default to 0.8 + """ + + enable_deduping: bool = proto.Field( + proto.BOOL, + number=1, + ) + similarity_threshold: float = proto.Field( + proto.FLOAT, + number=2, + ) + + +class RaiSettings(proto.Message): + r"""Settings for Responsible AI checks. + + Attributes: + rai_category_configs (MutableSequence[google.cloud.dialogflow_v2.types.RaiSettings.RaiCategoryConfig]): + Configuration for a set of RAI categories. + """ + + class RaiCategoryConfig(proto.Message): + r"""Configuration for a specific RAI category. + + Attributes: + category (google.cloud.dialogflow_v2.types.RaiSettings.RaiCategoryConfig.RaiCategory): + Optional. The RAI category. + sensitivity_level (google.cloud.dialogflow_v2.types.RaiSettings.RaiCategoryConfig.SensitivityLevel): + Optional. The sensitivity level for this + category. + """ + + class RaiCategory(proto.Enum): + r"""Enum for RAI category. + + Values: + RAI_CATEGORY_UNSPECIFIED (0): + Default value. + DANGEROUS_CONTENT (1): + Dangerous content. + SEXUALLY_EXPLICIT (2): + Sexually explicit content. + HARASSMENT (3): + Harassment content. + HATE_SPEECH (4): + Hate speech content. + """ + RAI_CATEGORY_UNSPECIFIED = 0 + DANGEROUS_CONTENT = 1 + SEXUALLY_EXPLICIT = 2 + HARASSMENT = 3 + HATE_SPEECH = 4 + + class SensitivityLevel(proto.Enum): + r"""Enum for user-configurable sensitivity levels. + + Values: + SENSITIVITY_LEVEL_UNSPECIFIED (0): + Default value. If unspecified, the default behavior is: + + - DANGEROUS_CONTENT: BLOCK_FEW + - SEXUALLY_EXPLICIT: BLOCK_SOME + - HARASSMENT: BLOCK_SOME + - HATE_SPEECH: BLOCK_SOME + BLOCK_MOST (1): + Block most potentially sensitive responses. + BLOCK_SOME (2): + Block some potentially sensitive responses. + BLOCK_FEW (3): + Block a few potentially sensitive responses. + BLOCK_NONE (4): + No filtering for this category. + """ + SENSITIVITY_LEVEL_UNSPECIFIED = 0 + BLOCK_MOST = 1 + BLOCK_SOME = 2 + BLOCK_FEW = 3 + BLOCK_NONE = 4 + + category: "RaiSettings.RaiCategoryConfig.RaiCategory" = proto.Field( + proto.ENUM, + number=1, + enum="RaiSettings.RaiCategoryConfig.RaiCategory", + ) + sensitivity_level: "RaiSettings.RaiCategoryConfig.SensitivityLevel" = ( + proto.Field( + proto.ENUM, + number=2, + enum="RaiSettings.RaiCategoryConfig.SensitivityLevel", + ) + ) + + rai_category_configs: MutableSequence[RaiCategoryConfig] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=RaiCategoryConfig, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/generator_evaluation.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/generator_evaluation.py new file mode 100644 index 000000000000..f90d926aa5cc --- /dev/null +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/generator_evaluation.py @@ -0,0 +1,1032 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.dialogflow_v2.types import generator + +__protobuf__ = proto.module( + package="google.cloud.dialogflow.v2", + manifest={ + "CreateGeneratorEvaluationRequest", + "GetGeneratorEvaluationRequest", + "ListGeneratorEvaluationsRequest", + "ListGeneratorEvaluationsResponse", + "DeleteGeneratorEvaluationRequest", + "GeneratorEvaluation", + "SummarizationEvaluationMetrics", + "GeneratorEvaluationConfig", + "EvaluationStatus", + }, +) + + +class CreateGeneratorEvaluationRequest(proto.Message): + r"""Request of CreateGeneratorEvaluation. + + Attributes: + parent (str): + Required. The generator resource name. Format: + ``projects//locations//generators/`` + generator_evaluation (google.cloud.dialogflow_v2.types.GeneratorEvaluation): + Required. The generator evaluation to be + created. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + generator_evaluation: "GeneratorEvaluation" = proto.Field( + proto.MESSAGE, + number=2, + message="GeneratorEvaluation", + ) + + +class GetGeneratorEvaluationRequest(proto.Message): + r"""Request of GetGeneratorEvaluation. + + Attributes: + name (str): + Required. The generator evaluation resource name. Format: + ``projects//locations//generators//evaluations/`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListGeneratorEvaluationsRequest(proto.Message): + r"""Request of ListGeneratorEvaluations. + + Attributes: + parent (str): + Required. The generator resource name. Format: + ``projects//locations//generators/`` + Wildcard value ``-`` is supported on generator_id to list + evaluations across all generators under same project. + page_size (int): + Optional. Maximum number of evaluations to + return in a single page. By default 100 and at + most 1000. + page_token (str): + Optional. The next_page_token value returned from a previous + list request. + """ + + 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, + ) + + +class ListGeneratorEvaluationsResponse(proto.Message): + r"""Response of ListGeneratorEvaluations. + + Attributes: + generator_evaluations (MutableSequence[google.cloud.dialogflow_v2.types.GeneratorEvaluation]): + The list of evaluations to return. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + generator_evaluations: MutableSequence["GeneratorEvaluation"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="GeneratorEvaluation", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteGeneratorEvaluationRequest(proto.Message): + r"""Request of DeleteGeneratorEvaluation. + + Attributes: + name (str): + Required. The generator evaluation resource name. Format: + ``projects//locations//generators// evaluations/`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GeneratorEvaluation(proto.Message): + r"""Represents evaluation result of a generator. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Output only. Identifier. The resource name of the + evaluation. Format: + ``projects//locations//generators// evaluations/`` + display_name (str): + Optional. The display name of the generator + evaluation. At most 64 bytes long. + generator_evaluation_config (google.cloud.dialogflow_v2.types.GeneratorEvaluationConfig): + Required. The configuration of the evaluation + task. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Creation time of this generator + evaluation. + complete_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Completion time of this + generator evaluation. + initial_generator (google.cloud.dialogflow_v2.types.Generator): + Required. The initial generator that was used + when creating this evaluation. This is a copy of + the generator read from storage when creating + the evaluation. + summarization_metrics (google.cloud.dialogflow_v2.types.SummarizationEvaluationMetrics): + Output only. Only available when the + summarization generator is provided. + + This field is a member of `oneof`_ ``metrics``. + evaluation_status (google.cloud.dialogflow_v2.types.EvaluationStatus): + Output only. The result status of the + evaluation pipeline. Provides the status + information including if the evaluation is still + in progress, completed or failed with certain + error and user actionable message. + satisfies_pzs (bool): + Output only. A read only boolean field + reflecting Zone Separation status of the model. + The field is an aggregated value of ZS status of + its underlying dependencies. See more details in + go/zicy-resource-placement#resource-status + + This field is a member of `oneof`_ ``_satisfies_pzs``. + satisfies_pzi (bool): + Output only. A read only boolean field + reflecting Zone Isolation status of the model. + The field is an aggregated value of ZI status of + its underlying dependencies. See more details in + go/zicy-resource-placement#resource-status + + This field is a member of `oneof`_ ``_satisfies_pzi``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + generator_evaluation_config: "GeneratorEvaluationConfig" = proto.Field( + proto.MESSAGE, + number=3, + message="GeneratorEvaluationConfig", + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + complete_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + initial_generator: generator.Generator = proto.Field( + proto.MESSAGE, + number=5, + message=generator.Generator, + ) + summarization_metrics: "SummarizationEvaluationMetrics" = proto.Field( + proto.MESSAGE, + number=6, + oneof="metrics", + message="SummarizationEvaluationMetrics", + ) + evaluation_status: "EvaluationStatus" = proto.Field( + proto.MESSAGE, + number=10, + message="EvaluationStatus", + ) + satisfies_pzs: bool = proto.Field( + proto.BOOL, + number=11, + optional=True, + ) + satisfies_pzi: bool = proto.Field( + proto.BOOL, + number=12, + optional=True, + ) + + +class SummarizationEvaluationMetrics(proto.Message): + r"""Evaluation metrics for summarization generator. + + Attributes: + summarization_evaluation_results (MutableSequence[google.cloud.dialogflow_v2.types.SummarizationEvaluationMetrics.SummarizationEvaluationResult]): + Output only. A list of evaluation results per + conversation(&summary), metric and section. + summarization_evaluation_merged_results_uri (str): + Output only. User bucket uri for merged + evaluation score and aggregation score csv. + overall_metrics (MutableSequence[google.cloud.dialogflow_v2.types.SummarizationEvaluationMetrics.OverallScoresByMetric]): + Output only. A list of aggregated(average) + scores per metric section. + overall_section_tokens (MutableSequence[google.cloud.dialogflow_v2.types.SummarizationEvaluationMetrics.SectionToken]): + Output only. Overall token per section. This + is an aggregated(sum) result of input token of + summary acorss all conversations that are + selected for summarization evaluation. + conversation_details (MutableSequence[google.cloud.dialogflow_v2.types.SummarizationEvaluationMetrics.ConversationDetail]): + Output only. List of conversation details. + """ + + class AccuracyDecomposition(proto.Message): + r"""Decomposition details for accuracy. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + point (str): + Output only. The breakdown point of the + summary. + accuracy_reasoning (str): + Output only. The accuracy reasoning of the + breakdown point. + is_accurate (bool): + Output only. Whether the breakdown point is + accurate or not. + + This field is a member of `oneof`_ ``_is_accurate``. + """ + + point: str = proto.Field( + proto.STRING, + number=1, + ) + accuracy_reasoning: str = proto.Field( + proto.STRING, + number=2, + ) + is_accurate: bool = proto.Field( + proto.BOOL, + number=3, + optional=True, + ) + + class AdherenceDecomposition(proto.Message): + r"""Decomposition details for adherence. + + Attributes: + point (str): + Output only. The breakdown point of the given + instructions. + adherence_reasoning (str): + Output only. The adherence reasoning of the + breakdown point. + is_adherent (bool): + Output only. Whether the breakdown point is + adherent or not. + """ + + point: str = proto.Field( + proto.STRING, + number=1, + ) + adherence_reasoning: str = proto.Field( + proto.STRING, + number=2, + ) + is_adherent: bool = proto.Field( + proto.BOOL, + number=3, + ) + + class AdherenceRubric(proto.Message): + r"""Rubric result of the adherence evaluation. A rubric is ued to + determine if the summary adheres to all aspects of the given + instructions. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + question (str): + Output only. The question generated from + instruction that used to evaluate summary. + reasoning (str): + Output only. The reasoning of the rubric + question is addressed or not. + is_addressed (bool): + Output only. A boolean that indicates whether + the rubric question is addressed or not. + + This field is a member of `oneof`_ ``_is_addressed``. + """ + + question: str = proto.Field( + proto.STRING, + number=1, + ) + reasoning: str = proto.Field( + proto.STRING, + number=2, + ) + is_addressed: bool = proto.Field( + proto.BOOL, + number=3, + optional=True, + ) + + class CompletenessRubric(proto.Message): + r"""Rubric details of the completeness evaluation result. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + question (str): + Output only. The question generated from + instruction that used to evaluate summary. + is_addressed (bool): + Output only. A boolean that indicates whether + the rubric question is addressed or not. + + This field is a member of `oneof`_ ``_is_addressed``. + """ + + question: str = proto.Field( + proto.STRING, + number=1, + ) + is_addressed: bool = proto.Field( + proto.BOOL, + number=2, + optional=True, + ) + + class Decomposition(proto.Message): + r"""Decomposition 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: + accuracy_decomposition (google.cloud.dialogflow_v2.types.SummarizationEvaluationMetrics.AccuracyDecomposition): + only available for accuracy metric. + + This field is a member of `oneof`_ ``decomposition``. + adherence_decomposition (google.cloud.dialogflow_v2.types.SummarizationEvaluationMetrics.AdherenceDecomposition): + only available for adherence metric. + + This field is a member of `oneof`_ ``decomposition``. + """ + + accuracy_decomposition: "SummarizationEvaluationMetrics.AccuracyDecomposition" = proto.Field( + proto.MESSAGE, + number=1, + oneof="decomposition", + message="SummarizationEvaluationMetrics.AccuracyDecomposition", + ) + adherence_decomposition: "SummarizationEvaluationMetrics.AdherenceDecomposition" = proto.Field( + proto.MESSAGE, + number=2, + oneof="decomposition", + message="SummarizationEvaluationMetrics.AdherenceDecomposition", + ) + + class EvaluationResult(proto.Message): + r"""Evaluation result that contains one of accuracy, adherence or + completeness evaluation result. + + 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: + accuracy_decomposition (google.cloud.dialogflow_v2.types.SummarizationEvaluationMetrics.AccuracyDecomposition): + Only available for accuracy metric. + + This field is a member of `oneof`_ ``result``. + adherence_rubric (google.cloud.dialogflow_v2.types.SummarizationEvaluationMetrics.AdherenceRubric): + Only available for adherence metric. + + This field is a member of `oneof`_ ``result``. + completeness_rubric (google.cloud.dialogflow_v2.types.SummarizationEvaluationMetrics.CompletenessRubric): + Only available for completeness metric. + + This field is a member of `oneof`_ ``result``. + """ + + accuracy_decomposition: "SummarizationEvaluationMetrics.AccuracyDecomposition" = proto.Field( + proto.MESSAGE, + number=1, + oneof="result", + message="SummarizationEvaluationMetrics.AccuracyDecomposition", + ) + adherence_rubric: "SummarizationEvaluationMetrics.AdherenceRubric" = ( + proto.Field( + proto.MESSAGE, + number=2, + oneof="result", + message="SummarizationEvaluationMetrics.AdherenceRubric", + ) + ) + completeness_rubric: "SummarizationEvaluationMetrics.CompletenessRubric" = ( + proto.Field( + proto.MESSAGE, + number=3, + oneof="result", + message="SummarizationEvaluationMetrics.CompletenessRubric", + ) + ) + + class SummarizationEvaluationResult(proto.Message): + r"""Evaluation result per conversation(&summary), metric and + section. + + Attributes: + session_id (str): + Output only. conversation session id + metric (str): + Output only. metric name, e.g. accuracy, + completeness, adherence, etc. + section (str): + Output only. section/task name, e.g. action, + situation, etc + score (float): + Output only. score calculated from + decompositions + section_summary (str): + Output only. Summary of this section + decompositions (MutableSequence[google.cloud.dialogflow_v2.types.SummarizationEvaluationMetrics.Decomposition]): + Output only. List of decompostion details + evaluation_results (MutableSequence[google.cloud.dialogflow_v2.types.SummarizationEvaluationMetrics.EvaluationResult]): + Output only. List of evaluation results. + """ + + session_id: str = proto.Field( + proto.STRING, + number=1, + ) + metric: str = proto.Field( + proto.STRING, + number=2, + ) + section: str = proto.Field( + proto.STRING, + number=3, + ) + score: float = proto.Field( + proto.FLOAT, + number=4, + ) + section_summary: str = proto.Field( + proto.STRING, + number=6, + ) + decompositions: MutableSequence[ + "SummarizationEvaluationMetrics.Decomposition" + ] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message="SummarizationEvaluationMetrics.Decomposition", + ) + evaluation_results: MutableSequence[ + "SummarizationEvaluationMetrics.EvaluationResult" + ] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message="SummarizationEvaluationMetrics.EvaluationResult", + ) + + class OverallScoresByMetric(proto.Message): + r"""Overall performance per metric. This is the aggregated score + for each metric across all conversations that are selected for + summarization evaluation. + + Attributes: + metric (str): + Output only. Metric name. e.g. accuracy, + adherence, completeness. + """ + + metric: str = proto.Field( + proto.STRING, + number=1, + ) + + class SectionToken(proto.Message): + r"""A pair of section name and input token count of the input + summary section. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + section (str): + Output only. The name of the summary + instruction. + token_count (int): + Output only. Token count. + + This field is a member of `oneof`_ ``_token_count``. + """ + + section: str = proto.Field( + proto.STRING, + number=1, + ) + token_count: int = proto.Field( + proto.INT64, + number=2, + optional=True, + ) + + class ConversationDetail(proto.Message): + r"""Aggregated evaluation result on conversation level. This + conatins evaluation results of all the metrics and sections. + + Attributes: + message_entries (MutableSequence[google.cloud.dialogflow_v2.types.MessageEntry]): + Output only. Conversation transcript that + used for summarization evaluation as a + reference. + summary_sections (MutableSequence[google.cloud.dialogflow_v2.types.SummarySuggestion.SummarySection]): + Output only. Summary sections that used for + summarization evaluation as a reference. + metric_details (MutableSequence[google.cloud.dialogflow_v2.types.SummarizationEvaluationMetrics.ConversationDetail.MetricDetail]): + Output only. List of metric details. + section_tokens (MutableSequence[google.cloud.dialogflow_v2.types.SummarizationEvaluationMetrics.SectionToken]): + Output only. Conversation level token count + per section. This is an aggregated(sum) result + of input token of summary acorss all metrics for + a single conversation. + """ + + class MetricDetail(proto.Message): + r"""Aggregated result on metric level. This conatins the + evaluation results of all the sections. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + metric (str): + Output only. Metrics name. e.g. accuracy, + adherence, completeness. + score (float): + Output only. Aggregated(average) score on + this metric across all sections. + + This field is a member of `oneof`_ ``_score``. + section_details (MutableSequence[google.cloud.dialogflow_v2.types.SummarizationEvaluationMetrics.ConversationDetail.MetricDetail.SectionDetail]): + Output only. List of section details. + """ + + class SectionDetail(proto.Message): + r"""Section level result. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + section (str): + Output only. The name of the summary + instruction. + score (float): + Output only. Aggregated(average) score on + this section across all evaluation results. + Either decompositions or rubrics. + + This field is a member of `oneof`_ ``_score``. + section_summary (str): + Output only. Summary for this section + evaluation_results (MutableSequence[google.cloud.dialogflow_v2.types.SummarizationEvaluationMetrics.EvaluationResult]): + Output only. List of evaluation result. The + list only contains one kind of the evaluation + result. + """ + + section: str = proto.Field( + proto.STRING, + number=1, + ) + score: float = proto.Field( + proto.FLOAT, + number=2, + optional=True, + ) + section_summary: str = proto.Field( + proto.STRING, + number=4, + ) + evaluation_results: MutableSequence[ + "SummarizationEvaluationMetrics.EvaluationResult" + ] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message="SummarizationEvaluationMetrics.EvaluationResult", + ) + + metric: str = proto.Field( + proto.STRING, + number=1, + ) + score: float = proto.Field( + proto.FLOAT, + number=2, + optional=True, + ) + section_details: MutableSequence[ + "SummarizationEvaluationMetrics.ConversationDetail.MetricDetail.SectionDetail" + ] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message="SummarizationEvaluationMetrics.ConversationDetail.MetricDetail.SectionDetail", + ) + + message_entries: MutableSequence[generator.MessageEntry] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=generator.MessageEntry, + ) + summary_sections: MutableSequence[ + generator.SummarySuggestion.SummarySection + ] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=generator.SummarySuggestion.SummarySection, + ) + metric_details: MutableSequence[ + "SummarizationEvaluationMetrics.ConversationDetail.MetricDetail" + ] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="SummarizationEvaluationMetrics.ConversationDetail.MetricDetail", + ) + section_tokens: MutableSequence[ + "SummarizationEvaluationMetrics.SectionToken" + ] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="SummarizationEvaluationMetrics.SectionToken", + ) + + summarization_evaluation_results: MutableSequence[ + SummarizationEvaluationResult + ] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=SummarizationEvaluationResult, + ) + summarization_evaluation_merged_results_uri: str = proto.Field( + proto.STRING, + number=5, + ) + overall_metrics: MutableSequence[OverallScoresByMetric] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=OverallScoresByMetric, + ) + overall_section_tokens: MutableSequence[SectionToken] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=SectionToken, + ) + conversation_details: MutableSequence[ConversationDetail] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=ConversationDetail, + ) + + +class GeneratorEvaluationConfig(proto.Message): + r"""Generator evaluation input config. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + input_data_config (google.cloud.dialogflow_v2.types.GeneratorEvaluationConfig.InputDataConfig): + Required. The config/source of input data. + output_gcs_bucket_path (str): + Required. The output Cloud Storage bucket path to store eval + files, e.g. per_summary_accuracy_score report. This path is + provided by customer and files stored in it are visible to + customer, no internal data should be stored in this path. + summarization_config (google.cloud.dialogflow_v2.types.GeneratorEvaluationConfig.SummarizationConfig): + Evaluation configs for summarization + generator. + + This field is a member of `oneof`_ ``evaluation_feature_config``. + """ + + class InputDataSourceType(proto.Enum): + r"""Enumeration of input data source type. + + Values: + INPUT_DATA_SOURCE_TYPE_UNSPECIFIED (0): + Unspecified InputDataSourceType. Should not + be used. + AGENT_ASSIST_CONVERSATIONS (1): + Fetch data from Agent Assist storage. If this source type is + chosen, input_data_config.start_time and + input_data_config.end_timestamp must be provided. + INSIGHTS_CONVERSATIONS (2): + Fetch data from Insights storage. If this source type is + chosen, input_data_config.start_time and + input_data_config.end_timestamp must be provided. + """ + INPUT_DATA_SOURCE_TYPE_UNSPECIFIED = 0 + AGENT_ASSIST_CONVERSATIONS = 1 + INSIGHTS_CONVERSATIONS = 2 + + class AgentAssistInputDataConfig(proto.Message): + r"""The distinctive configs for Agent Assist conversations as the + conversation source. + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + Required. The start of the time range for + conversations to be evaluated. Only + conversations created at or after this timestamp + will be sampled. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Required. The end of the time range for + conversations to be evaluated. Only + conversations ended at or before this timestamp + will be sampled. + """ + + start_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, + ) + + class DatasetInputDataConfig(proto.Message): + r"""The distinctive configs for dataset as the conversation + source. + + Attributes: + dataset (str): + Required. The identifier of the dataset to be evaluated. + Format: + ``projects//locations//datasets/``. + """ + + dataset: str = proto.Field( + proto.STRING, + number=1, + ) + + class InputDataConfig(proto.Message): + r"""Input data config 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: + input_data_source_type (google.cloud.dialogflow_v2.types.GeneratorEvaluationConfig.InputDataSourceType): + Required. The source type of input data. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. The start timestamp to fetch + conversation data. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. The end timestamp to fetch + conversation data. + sample_size (int): + Optional. Desired number of + conversation-summary pairs to be evaluated. + is_summary_generation_allowed (bool): + Optional. Whether the summary generation is + allowed when the pre-existing qualified + summaries are insufficient to cover the sample + size. + summary_generation_option (google.cloud.dialogflow_v2.types.GeneratorEvaluationConfig.InputDataConfig.SummaryGenerationOption): + Optional. Option to control whether summaries + are generated during evaluation. + agent_assist_input_data_config (google.cloud.dialogflow_v2.types.GeneratorEvaluationConfig.AgentAssistInputDataConfig): + The distinctive configs for Agent Assist + conversations as the conversation source. + + This field is a member of `oneof`_ ``source_specific_config``. + dataset_input_data_config (google.cloud.dialogflow_v2.types.GeneratorEvaluationConfig.DatasetInputDataConfig): + The distinctive configs for dataset as the + conversation source. + + This field is a member of `oneof`_ ``source_specific_config``. + """ + + class SummaryGenerationOption(proto.Enum): + r"""Summary generation options. + + Values: + SUMMARY_GENERATION_OPTION_UNSPECIFIED (0): + Default option will not be used + ALWAYS_GENERATE (1): + Always Generate summary for all + conversations. + GENERATE_IF_MISSING (2): + Gnerate only missing summaries. + DO_NOT_GENERATE (3): + Do not generate new summaries. Only use + existing summaries found. + """ + SUMMARY_GENERATION_OPTION_UNSPECIFIED = 0 + ALWAYS_GENERATE = 1 + GENERATE_IF_MISSING = 2 + DO_NOT_GENERATE = 3 + + input_data_source_type: "GeneratorEvaluationConfig.InputDataSourceType" = ( + proto.Field( + proto.ENUM, + number=1, + enum="GeneratorEvaluationConfig.InputDataSourceType", + ) + ) + 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, + ) + sample_size: int = proto.Field( + proto.INT32, + number=4, + ) + is_summary_generation_allowed: bool = proto.Field( + proto.BOOL, + number=5, + ) + summary_generation_option: "GeneratorEvaluationConfig.InputDataConfig.SummaryGenerationOption" = proto.Field( + proto.ENUM, + number=8, + enum="GeneratorEvaluationConfig.InputDataConfig.SummaryGenerationOption", + ) + agent_assist_input_data_config: "GeneratorEvaluationConfig.AgentAssistInputDataConfig" = proto.Field( + proto.MESSAGE, + number=6, + oneof="source_specific_config", + message="GeneratorEvaluationConfig.AgentAssistInputDataConfig", + ) + dataset_input_data_config: "GeneratorEvaluationConfig.DatasetInputDataConfig" = proto.Field( + proto.MESSAGE, + number=7, + oneof="source_specific_config", + message="GeneratorEvaluationConfig.DatasetInputDataConfig", + ) + + class SummarizationConfig(proto.Message): + r"""Evaluation configs for summarization generator. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + enable_accuracy_evaluation (bool): + Optional. Enable accuracy evaluation. + accuracy_evaluation_version (str): + Optional. Version for summarization accuracy. + This will determine the prompt and model used at + backend. + enable_completeness_evaluation (bool): + Optional. Enable completeness evaluation. + completeness_evaluation_version (str): + Optional. Version for summarization + completeness. This will determine the prompt and + model used at backend. + evaluator_version (str): + Optional. Version for summarization + evaluation. + + This field is a member of `oneof`_ ``_evaluator_version``. + """ + + enable_accuracy_evaluation: bool = proto.Field( + proto.BOOL, + number=1, + ) + accuracy_evaluation_version: str = proto.Field( + proto.STRING, + number=2, + ) + enable_completeness_evaluation: bool = proto.Field( + proto.BOOL, + number=3, + ) + completeness_evaluation_version: str = proto.Field( + proto.STRING, + number=4, + ) + evaluator_version: str = proto.Field( + proto.STRING, + number=5, + optional=True, + ) + + input_data_config: InputDataConfig = proto.Field( + proto.MESSAGE, + number=1, + message=InputDataConfig, + ) + output_gcs_bucket_path: str = proto.Field( + proto.STRING, + number=2, + ) + summarization_config: SummarizationConfig = proto.Field( + proto.MESSAGE, + number=3, + oneof="evaluation_feature_config", + message=SummarizationConfig, + ) + + +class EvaluationStatus(proto.Message): + r"""A common evalaution pipeline status. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + done (bool): + Output only. If the value is ``false``, it means the + evaluation is still in progress. If ``true``, the operation + is completed, and either ``error`` or ``response`` is + available. + + This field is a member of `oneof`_ ``_done``. + pipeline_status (google.rpc.status_pb2.Status): + Output only. The error result of the + evaluation in case of failure in evaluation + pipeline. + """ + + done: bool = proto.Field( + proto.BOOL, + number=1, + optional=True, + ) + pipeline_status: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/operations.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/operations.py new file mode 100644 index 000000000000..1ae744fb067b --- /dev/null +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/operations.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.dialogflow.v2", + manifest={ + "GeneratorEvaluationOperationMetadata", + }, +) + + +class GeneratorEvaluationOperationMetadata(proto.Message): + r"""Metadata for a + [GeneratorEvaluations.CreateGeneratorEvaluation][google.cloud.dialogflow.v2.GeneratorEvaluations.CreateGeneratorEvaluation] + operation. + + Attributes: + generator_evaluation (str): + Output only. The resource name of the generator evaluation. + Format: + ``projects//locations//generators//evaluations/`` + """ + + generator_evaluation: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/participant.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/participant.py index 3e9faabbb6b5..78931547e873 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/participant.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/participant.py @@ -144,6 +144,18 @@ class Participant(proto.Message): key: "user" value: "agent" } + agent_desktop_source (google.cloud.dialogflow_v2.types.Participant.AgentDesktopSource): + Optional. For tracking the utilization of prebuilt Agent + Assist integration modules. This field is only inscope for + Integration type that include UI Modules, Backend Modules, + and Agent Desktop connector, it is out of scope for CCaaS + and Direct Integration. For each human agent, prebuilt UI + Modules needs to trigger the UpdateParticipant API to update + this field. Both + [CreateParticipantRequest][google.cloud.dialogflow.v2.CreateParticipantRequest.participant] + and + [UpdateParticipantRequest][google.cloud.dialogflow.v2.UpdateParticipantRequest.participant] + will be supported. """ class Role(proto.Enum): @@ -167,6 +179,33 @@ class Role(proto.Enum): AUTOMATED_AGENT = 2 END_USER = 3 + class AgentDesktopSource(proto.Enum): + r"""Enumeration of the Agent Desktop Source when using prebuilt + Agent Assist integration modules. + + Values: + AGENT_DESKTOP_SOURCE_UNSPECIFIED (0): + Agent Desktop Source is not specified. + LIVE_PERSON (1): + Agent Desktop Source is Live Person. + GENESYS_CLOUD (2): + Agent Desktop Source is Genesys Cloud. + TWILIO (3): + Agent Desktop Source is Twilio. + SALESFORCE (4): + Agent Desktop Source is Salesforce. + OTHER (8): + UI Modules are in use but the desktop is + either not currently released or setting this + field to the applicable desktop. + """ + AGENT_DESKTOP_SOURCE_UNSPECIFIED = 0 + LIVE_PERSON = 1 + GENESYS_CLOUD = 2 + TWILIO = 3 + SALESFORCE = 4 + OTHER = 8 + name: str = proto.Field( proto.STRING, number=1, @@ -189,6 +228,11 @@ class Role(proto.Enum): proto.STRING, number=8, ) + agent_desktop_source: AgentDesktopSource = proto.Field( + proto.ENUM, + number=10, + enum=AgentDesktopSource, + ) class Message(proto.Message): @@ -1759,21 +1803,72 @@ class MessageAnnotation(proto.Message): class SuggestionInput(proto.Message): - r"""Represents the selection of a suggestion. + r"""Represents the action to take for a tool call that requires + confirmation. Attributes: answer_record (str): - Required. The ID of a suggestion selected by the human - agent. The suggestion(s) were generated in a previous call - to request Dialogflow assist. The format is: + Required. Format: ``projects//locations//answerRecords/`` - where is an alphanumeric string. + The answer record associated with the tool call. + parameters (google.protobuf.struct_pb2.Struct): + Optional. Parameters to be used for the tool + call. If not provided, the tool will be called + without any parameters. + action (google.cloud.dialogflow_v2.types.SuggestionInput.Action): + Optional. The type of action to take with the + tool. + send_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. Time when the current suggest input + is sent. For tool calls, this timestamp (along + with the answer record) will be included in the + corresponding tool call result so that it can be + identified. """ + class Action(proto.Enum): + r"""Indicate what type of action to take with the tool call. + + Values: + ACTION_UNSPECIFIED (0): + Action not specified. + CANCEL (1): + Indicates the user chooses to not make the + tool call. It is only applicable to tool calls + that are waiting for user confirmation. + REVISE (2): + Makes the tool call with provided parameters. + This action is intended for tool calls that only + read but not write data. + CONFIRM (3): + Makes the tool call with provided parameters. + This action is intended for tool calls that may + write data. + """ + ACTION_UNSPECIFIED = 0 + CANCEL = 1 + REVISE = 2 + CONFIRM = 3 + answer_record: str = proto.Field( proto.STRING, number=1, ) + parameters: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=4, + message=struct_pb2.Struct, + ) + action: Action = proto.Field( + proto.ENUM, + number=5, + enum=Action, + ) + send_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) class AssistQueryParameters(proto.Message): diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/sip_trunk.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/sip_trunk.py new file mode 100644 index 000000000000..ba066ca629bf --- /dev/null +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/sip_trunk.py @@ -0,0 +1,350 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.dialogflow.v2", + manifest={ + "CreateSipTrunkRequest", + "DeleteSipTrunkRequest", + "ListSipTrunksRequest", + "ListSipTrunksResponse", + "GetSipTrunkRequest", + "UpdateSipTrunkRequest", + "SipTrunk", + "Connection", + }, +) + + +class CreateSipTrunkRequest(proto.Message): + r"""The request message for + [SipTrunks.CreateSipTrunk][google.cloud.dialogflow.v2.SipTrunks.CreateSipTrunk]. + + Attributes: + parent (str): + Required. The location to create a SIP trunk for. Format: + ``projects//locations/``. + sip_trunk (google.cloud.dialogflow_v2.types.SipTrunk): + Required. The SIP trunk to create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + sip_trunk: "SipTrunk" = proto.Field( + proto.MESSAGE, + number=2, + message="SipTrunk", + ) + + +class DeleteSipTrunkRequest(proto.Message): + r"""The request message for + [SipTrunks.DeleteSipTrunk][google.cloud.dialogflow.v2.SipTrunks.DeleteSipTrunk]. + + Attributes: + name (str): + Required. The name of the SIP trunk to delete. Format: + ``projects//locations//sipTrunks/``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListSipTrunksRequest(proto.Message): + r"""The request message for + [SipTrunks.ListSipTrunks][google.cloud.dialogflow.v2.SipTrunks.ListSipTrunks]. + + Attributes: + parent (str): + Required. The location to list SIP trunks from. Format: + ``projects//locations/``. + page_size (int): + Optional. The maximum number of items to + return in a single page. By default 100 and at + most 1000. + page_token (str): + Optional. The next_page_token value returned from a previous + list request. + """ + + 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, + ) + + +class ListSipTrunksResponse(proto.Message): + r"""The response message for + [SipTrunks.ListSipTrunks][google.cloud.dialogflow.v2.SipTrunks.ListSipTrunks]. + + Attributes: + sip_trunks (MutableSequence[google.cloud.dialogflow_v2.types.SipTrunk]): + The list of SIP trunks. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + sip_trunks: MutableSequence["SipTrunk"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="SipTrunk", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetSipTrunkRequest(proto.Message): + r"""The request message for + [SipTrunks.GetSipTrunk][google.cloud.dialogflow.v2.SipTrunks.GetSipTrunk]. + + Attributes: + name (str): + Required. The name of the SIP trunk to delete. Format: + ``projects//locations//sipTrunks/``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateSipTrunkRequest(proto.Message): + r"""The request message for + [SipTrunks.UpdateSipTrunk][google.cloud.dialogflow.v2.SipTrunks.UpdateSipTrunk]. + + Attributes: + sip_trunk (google.cloud.dialogflow_v2.types.SipTrunk): + Required. The SipTrunk to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The mask to control which fields + get updated. If the mask is not present, all + fields will be updated. + """ + + sip_trunk: "SipTrunk" = proto.Field( + proto.MESSAGE, + number=1, + message="SipTrunk", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class SipTrunk(proto.Message): + r"""SipTrunk is the resource that represents a SIP trunk to + connect to Google Telephony platform SIP trunking service. + + Attributes: + name (str): + Identifier. The unique identifier of the SIP trunk. Format: + ``projects//locations//sipTrunks/``. + expected_hostname (MutableSequence[str]): + Required. The expected hostnames in the peer + certificate from partner that is used for TLS + authentication. + connections (MutableSequence[google.cloud.dialogflow_v2.types.Connection]): + Output only. Connections of the SIP trunk. + display_name (str): + Optional. Human readable alias for this + trunk. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + expected_hostname: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + connections: MutableSequence["Connection"] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="Connection", + ) + display_name: str = proto.Field( + proto.STRING, + number=4, + ) + + +class Connection(proto.Message): + r"""Represents a connection for SIP Trunk. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + connection_id (str): + Output only. The unique identifier of the SIP + Trunk connection. + state (google.cloud.dialogflow_v2.types.Connection.State): + Output only. State of the connection. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the connection status + changed. + + This field is a member of `oneof`_ ``_update_time``. + error_details (google.cloud.dialogflow_v2.types.Connection.ErrorDetails): + Output only. The error details for the + connection. Only populated when authentication + errors occur. + + This field is a member of `oneof`_ ``_error_details``. + """ + + class State(proto.Enum): + r"""The state of Sip Trunk connection. + + Values: + STATE_UNSPECIFIED (0): + SIP Trunk connection state is Not specified. + CONNECTED (1): + SIP Trunk connection is connected. + DISCONNECTED (2): + SIP Trunk connection is disconnected. + AUTHENTICATION_FAILED (3): + SIP Trunk connection has authentication + error. + KEEPALIVE (4): + SIP Trunk connection is keepalive. + """ + STATE_UNSPECIFIED = 0 + CONNECTED = 1 + DISCONNECTED = 2 + AUTHENTICATION_FAILED = 3 + KEEPALIVE = 4 + + class CertificateState(proto.Enum): + r"""The state of Sip Trunk certificate authentication. + + Values: + CERTIFICATE_STATE_UNSPECIFIED (0): + Certificate state is not specified. + CERTIFICATE_VALID (1): + Certificate is valid. + CERTIFICATE_INVALID (2): + Catch all for any error not specified. + CERTIFICATE_EXPIRED (3): + Certificate leaf node has expired. + CERTIFICATE_HOSTNAME_NOT_FOUND (4): + There is no hostname defined to authenticate + in SipTrunkingServer. + CERTIFICATE_UNAUTHENTICATED (5): + No path found from the leaf certificate to + any root. + CERTIFICATE_TRUST_STORE_NOT_FOUND (6): + Trust store does not exist. + CERTIFICATE_HOSTNAME_INVALID_FORMAT (7): + Hostname has invalid format. + CERTIFICATE_QUOTA_EXCEEDED (8): + Certificate has exhausted its quota. + """ + CERTIFICATE_STATE_UNSPECIFIED = 0 + CERTIFICATE_VALID = 1 + CERTIFICATE_INVALID = 2 + CERTIFICATE_EXPIRED = 3 + CERTIFICATE_HOSTNAME_NOT_FOUND = 4 + CERTIFICATE_UNAUTHENTICATED = 5 + CERTIFICATE_TRUST_STORE_NOT_FOUND = 6 + CERTIFICATE_HOSTNAME_INVALID_FORMAT = 7 + CERTIFICATE_QUOTA_EXCEEDED = 8 + + class ErrorDetails(proto.Message): + r"""The error details of Sip Trunk connection authentication. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + certificate_state (google.cloud.dialogflow_v2.types.Connection.CertificateState): + Output only. The status of the certificate + authentication. + + This field is a member of `oneof`_ ``_certificate_state``. + error_message (str): + The error message provided from SIP trunking + auth service + + This field is a member of `oneof`_ ``_error_message``. + """ + + certificate_state: "Connection.CertificateState" = proto.Field( + proto.ENUM, + number=1, + optional=True, + enum="Connection.CertificateState", + ) + error_message: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + + connection_id: str = proto.Field( + proto.STRING, + number=1, + ) + state: State = proto.Field( + proto.ENUM, + number=2, + enum=State, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + optional=True, + message=timestamp_pb2.Timestamp, + ) + error_details: ErrorDetails = proto.Field( + proto.MESSAGE, + number=4, + optional=True, + message=ErrorDetails, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/tool.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/tool.py new file mode 100644 index 000000000000..fd910fd892df --- /dev/null +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/tool.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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.dialogflow.v2", + manifest={ + "CreateToolRequest", + "GetToolRequest", + "ListToolsRequest", + "ListToolsResponse", + "DeleteToolRequest", + "UpdateToolRequest", + "Tool", + }, +) + + +class CreateToolRequest(proto.Message): + r"""Request message of CreateTool. + + Attributes: + parent (str): + Required. The project/location to create tool for. Format: + ``projects//locations/`` + tool (google.cloud.dialogflow_v2.types.Tool): + Required. The tool to create. + tool_id (str): + Optional. The ID to use for the tool, which will become the + final component of the tool's resource name. + + The tool ID must be compliant with the regression formula + ``[a-zA-Z][a-zA-Z0-9_-]*`` with the characters length in + range of [3,64]. If the field is not provide, an Id will be + auto-generated. If the field is provided, the caller is + responsible for + + 1. the uniqueness of the ID, otherwise the request will be + rejected. + 2. the consistency for whether to use custom ID or not under + a project to better ensure uniqueness. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + tool: "Tool" = proto.Field( + proto.MESSAGE, + number=2, + message="Tool", + ) + tool_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class GetToolRequest(proto.Message): + r"""Request message of GetTool. + + Attributes: + name (str): + Required. The tool resource name to retrieve. Format: + ``projects//locations//tools/`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListToolsRequest(proto.Message): + r"""Request message of ListTools. + + Attributes: + parent (str): + Required. The project/location to list tools for. Format: + ``projects//locations/`` + page_size (int): + Optional. Maximum number of conversation + models to return in a single page. Default to + 10. + page_token (str): + Optional. The next_page_token value returned from a previous + list request. + """ + + 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, + ) + + +class ListToolsResponse(proto.Message): + r"""Response of ListTools. + + Attributes: + tools (MutableSequence[google.cloud.dialogflow_v2.types.Tool]): + List of tools retrieved. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + tools: MutableSequence["Tool"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Tool", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteToolRequest(proto.Message): + r"""Request of DeleteTool. + + Attributes: + name (str): + Required. The tool resource name to delete. Format: + ``projects//locations//tools/`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateToolRequest(proto.Message): + r"""Request of UpdateTool. + + Attributes: + tool (google.cloud.dialogflow_v2.types.Tool): + Required. The tool to update. + The name field of tool is to identify the tool + to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to update. + """ + + tool: "Tool" = proto.Field( + proto.MESSAGE, + number=1, + message="Tool", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class Tool(proto.Message): + r"""Represents a 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: + name (str): + Output only. Identifier. The resource name of the tool. + Format: + ``projects//locations//tools/``. + tool_key (str): + Required. A human readable short name of the + tool, which should be unique within the project. + It should only contain letters, numbers, and + underscores, and it will be used by LLM to + identify the tool. + display_name (str): + Optional. A human readable short name of the + tool, to be shown on the UI. + description (str): + Optional. A human readable description of the + tool. + action_confirmation_requirement (MutableMapping[str, google.cloud.dialogflow_v2.types.Tool.ConfirmationRequirement]): + Optional. Confirmation requirement for the actions. Each key + is an action name in the action_schemas. If an action's + confirmation requirement is unspecified (either the key is + not present, or its value is + CONFIRMATION_REQUIREMENT_UNSPECIFIED), the requirement is + inferred from the action's method_type - confirmation is not + required if and only if method_type is GET. + extension_spec (google.cloud.dialogflow_v2.types.Tool.ExtensionTool): + Vertex extension tool specification. + + This field is a member of `oneof`_ ``specification``. + function_spec (google.cloud.dialogflow_v2.types.Tool.FunctionTool): + Client side executed function specification. + + This field is a member of `oneof`_ ``specification``. + connector_spec (google.cloud.dialogflow_v2.types.Tool.ConnectorTool): + Integration connectors tool specification. + + This field is a member of `oneof`_ ``specification``. + open_api_spec (google.cloud.dialogflow_v2.types.Tool.OpenApiTool): + OpenAPI tool. + + This field is a member of `oneof`_ ``specification``. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Creation time of this tool. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Update time of this tool. + satisfies_pzs (bool): + Output only. A read only boolean field + reflecting Zone Separation status of the tool. + If the field is absent, it means the status is + unknown. + + This field is a member of `oneof`_ ``_satisfies_pzs``. + satisfies_pzi (bool): + Output only. A read only boolean field + reflecting Zone Isolation status of the tool. If + the field is absent, it means the status is + unknown. + + This field is a member of `oneof`_ ``_satisfies_pzi``. + """ + + class ConfirmationRequirement(proto.Enum): + r"""Types of confirmation requirement. + + Values: + CONFIRMATION_REQUIREMENT_UNSPECIFIED (0): + Unspecified. Whether the action requires confirmation is + inferred from method_type. + REQUIRED (1): + Conformation is required. + NOT_REQUIRED (2): + Conformation is not required. + """ + CONFIRMATION_REQUIREMENT_UNSPECIFIED = 0 + REQUIRED = 1 + NOT_REQUIRED = 2 + + class MethodType(proto.Enum): + r"""The method type of the tool. + + Values: + METHOD_TYPE_UNSPECIFIED (0): + Unspecified. + GET (1): + GET method. + POST (2): + POST method. + PUT (3): + PUT method. + DELETE (4): + DELETE method. + PATCH (5): + PATCH method. + """ + METHOD_TYPE_UNSPECIFIED = 0 + GET = 1 + POST = 2 + PUT = 3 + DELETE = 4 + PATCH = 5 + + class ExtensionTool(proto.Message): + r"""An ExtensionTool is a way to use Vertex Extensions as a tool. + + Attributes: + name (str): + Required. The full name of the referenced vertex extension. + Format: + ``projects/{project}/locations/{location}/extensions/{extension}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + class FunctionTool(proto.Message): + r"""A Function tool describes the functions to be invoked on the + client side. + + Attributes: + input_schema (google.protobuf.struct_pb2.Struct): + Optional. The JSON schema is encapsulated in a + [google.protobuf.Struct][google.protobuf.Struct] to describe + the input of the function. This input is a JSON object that + contains the function's parameters as properties of the + object. + output_schema (google.protobuf.struct_pb2.Struct): + Optional. The JSON schema is encapsulated in a + [google.protobuf.Struct][google.protobuf.Struct] to describe + the output of the function. This output is a JSON object + that contains the function's parameters as properties of the + object. + method_type (google.cloud.dialogflow_v2.types.Tool.MethodType): + Optional. The method type of the function. If + not specified, the default value is GET. + """ + + input_schema: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=1, + message=struct_pb2.Struct, + ) + output_schema: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=2, + message=struct_pb2.Struct, + ) + method_type: "Tool.MethodType" = proto.Field( + proto.ENUM, + number=4, + enum="Tool.MethodType", + ) + + class OpenApiTool(proto.Message): + r"""An OpenAPI tool is a way to provide the Tool specifications + in the Open API schema format. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + text_schema (str): + Required. The OpenAPI schema specified as a + text. + + This field is a member of `oneof`_ ``schema``. + authentication (google.cloud.dialogflow_v2.types.Tool.Authentication): + Optional. Authentication information required + by the API. + tls_config (google.cloud.dialogflow_v2.types.Tool.TLSConfig): + Optional. TLS configuration for the HTTPS + verification. + service_directory_config (google.cloud.dialogflow_v2.types.Tool.ServiceDirectoryConfig): + Optional. Service Directory configuration. + """ + + text_schema: str = proto.Field( + proto.STRING, + number=1, + oneof="schema", + ) + authentication: "Tool.Authentication" = proto.Field( + proto.MESSAGE, + number=2, + message="Tool.Authentication", + ) + tls_config: "Tool.TLSConfig" = proto.Field( + proto.MESSAGE, + number=3, + message="Tool.TLSConfig", + ) + service_directory_config: "Tool.ServiceDirectoryConfig" = proto.Field( + proto.MESSAGE, + number=4, + message="Tool.ServiceDirectoryConfig", + ) + + class ConnectorTool(proto.Message): + r"""A ConnectorTool enabling using Integration Connectors + Connections as tools. + + Attributes: + name (str): + Required. The full resource name of the referenced + Integration Connectors Connection. Format: + 'projects/*/locations/*/connections/\*' + actions (MutableSequence[google.cloud.dialogflow_v2.types.Tool.ConnectorTool.Action]): + Required. Actions for the tool to use. + """ + + class Action(proto.Message): + r"""Configuration of a Connection operation for the tool to use. + + 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.dialogflow_v2.types.Tool.ConnectorTool.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.dialogflow_v2.types.Tool.ConnectorTool.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: "Tool.ConnectorTool.Action.EntityOperation.OperationType" = ( + proto.Field( + proto.ENUM, + number=2, + enum="Tool.ConnectorTool.Action.EntityOperation.OperationType", + ) + ) + + connection_action_id: str = proto.Field( + proto.STRING, + number=4, + oneof="action_spec", + ) + entity_operation: "Tool.ConnectorTool.Action.EntityOperation" = proto.Field( + proto.MESSAGE, + number=5, + oneof="action_spec", + message="Tool.ConnectorTool.Action.EntityOperation", + ) + input_fields: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + output_fields: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + actions: MutableSequence["Tool.ConnectorTool.Action"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="Tool.ConnectorTool.Action", + ) + + class Authentication(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.dialogflow_v2.types.Tool.Authentication.ApiKeyConfig): + Config for API key auth. + + This field is a member of `oneof`_ ``auth_config``. + oauth_config (google.cloud.dialogflow_v2.types.Tool.Authentication.OAuthConfig): + Config for OAuth. + + This field is a member of `oneof`_ ``auth_config``. + service_agent_auth_config (google.cloud.dialogflow_v2.types.Tool.Authentication.ServiceAgentAuthConfig): + Config for `Diglogflow service + agent `__ + auth. + + This field is a member of `oneof`_ ``auth_config``. + bearer_token_config (google.cloud.dialogflow_v2.types.Tool.Authentication.BearerTokenConfig): + Config for bearer token auth. + + This field is a member of `oneof`_ ``auth_config``. + """ + + class RequestLocation(proto.Enum): + r"""The location of the API key in the request. + + Values: + REQUEST_LOCATION_UNSPECIFIED (0): + Default value. This value is unused. + 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 + + class ApiKeyConfig(proto.Message): + r"""Config 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 (str): + Optional. The API key. If the ``secret_version_for_api_key`` + field is set, this field will be ignored. + secret_version_for_api_key (str): + Optional. The name of the SecretManager secret version + resource storing the API key. If this field is set, the + ``api_key`` field will be ignored. Format: + ``projects/{project}/secrets/{secret}/versions/{version}`` + request_location (google.cloud.dialogflow_v2.types.Tool.Authentication.RequestLocation): + Required. Key location in the request. + """ + + key_name: str = proto.Field( + proto.STRING, + number=1, + ) + api_key: str = proto.Field( + proto.STRING, + number=2, + ) + secret_version_for_api_key: str = proto.Field( + proto.STRING, + number=4, + ) + request_location: "Tool.Authentication.RequestLocation" = proto.Field( + proto.ENUM, + number=3, + enum="Tool.Authentication.RequestLocation", + ) + + class OAuthConfig(proto.Message): + r"""Config for authentication with OAuth. + + Attributes: + oauth_grant_type (google.cloud.dialogflow_v2.types.Tool.Authentication.OAuthConfig.OauthGrantType): + Required. OAuth grant types. + client_id (str): + Required. The client ID from the OAuth + provider. + client_secret (str): + Optional. The client secret from the OAuth provider. If the + ``secret_version_for_client_secret`` field is set, this + field will be ignored. + secret_version_for_client_secret (str): + Optional. The name of the SecretManager secret version + resource storing the client secret. If this field is set, + the ``client_secret`` field will be ignored. Format: + ``projects/{project}/secrets/{secret}/versions/{version}`` + 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): + Default value. This value is unused. + CLIENT_CREDENTIAL (1): + Represents the `client credential + flow `__. + """ + OAUTH_GRANT_TYPE_UNSPECIFIED = 0 + CLIENT_CREDENTIAL = 1 + + oauth_grant_type: "Tool.Authentication.OAuthConfig.OauthGrantType" = ( + proto.Field( + proto.ENUM, + number=1, + enum="Tool.Authentication.OAuthConfig.OauthGrantType", + ) + ) + client_id: str = proto.Field( + proto.STRING, + number=2, + ) + client_secret: str = proto.Field( + proto.STRING, + number=3, + ) + secret_version_for_client_secret: str = proto.Field( + proto.STRING, + number=6, + ) + token_endpoint: str = proto.Field( + proto.STRING, + number=4, + ) + scopes: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + + class ServiceAgentAuthConfig(proto.Message): + r"""Config for auth using `Dialogflow service + agent `__. + + Attributes: + service_agent_auth (google.cloud.dialogflow_v2.types.Tool.Authentication.ServiceAgentAuthConfig.ServiceAgentAuth): + Optional. Indicate the auth token type generated from the + `Diglogflow service + agent `__. + The generated token is sent in the Authorization header. + """ + + class ServiceAgentAuth(proto.Enum): + r"""Indicate the auth token type generated from the `Diaglogflow service + agent `__. + + Values: + SERVICE_AGENT_AUTH_UNSPECIFIED (0): + Service agent auth type unspecified. Default to ID_TOKEN. + ID_TOKEN (1): + Use `ID + token `__ + generated from service agent. This can be used to access + Cloud Function and Cloud Run after you grant Invoker role to + ``service-@gcp-sa-dialogflow.iam.gserviceaccount.com``. + ACCESS_TOKEN (2): + Use `access + token `__ + generated from service agent. This can be used to access + other Google Cloud APIs after you grant required roles to + ``service-@gcp-sa-dialogflow.iam.gserviceaccount.com``. + """ + SERVICE_AGENT_AUTH_UNSPECIFIED = 0 + ID_TOKEN = 1 + ACCESS_TOKEN = 2 + + service_agent_auth: "Tool.Authentication.ServiceAgentAuthConfig.ServiceAgentAuth" = proto.Field( + proto.ENUM, + number=1, + enum="Tool.Authentication.ServiceAgentAuthConfig.ServiceAgentAuth", + ) + + class BearerTokenConfig(proto.Message): + r"""Config for authentication using bearer token. + + Attributes: + token (str): + Optional. The text token appended to the text ``Bearer`` to + the request Authorization header. `Session parameters + reference `__ + can be used to pass the token dynamically, e.g. + ``$session.params.parameter-id``. + secret_version_for_token (str): + Optional. The name of the SecretManager secret version + resource storing the Bearer token. If this field is set, the + ``token`` field will be ignored. Format: + ``projects/{project}/secrets/{secret}/versions/{version}`` + """ + + token: str = proto.Field( + proto.STRING, + number=1, + ) + secret_version_for_token: str = proto.Field( + proto.STRING, + number=2, + ) + + api_key_config: "Tool.Authentication.ApiKeyConfig" = proto.Field( + proto.MESSAGE, + number=1, + oneof="auth_config", + message="Tool.Authentication.ApiKeyConfig", + ) + oauth_config: "Tool.Authentication.OAuthConfig" = proto.Field( + proto.MESSAGE, + number=2, + oneof="auth_config", + message="Tool.Authentication.OAuthConfig", + ) + service_agent_auth_config: "Tool.Authentication.ServiceAgentAuthConfig" = ( + proto.Field( + proto.MESSAGE, + number=3, + oneof="auth_config", + message="Tool.Authentication.ServiceAgentAuthConfig", + ) + ) + bearer_token_config: "Tool.Authentication.BearerTokenConfig" = proto.Field( + proto.MESSAGE, + number=4, + oneof="auth_config", + message="Tool.Authentication.BearerTokenConfig", + ) + + class TLSConfig(proto.Message): + r"""The TLS configuration. + + Attributes: + ca_certs (MutableSequence[google.cloud.dialogflow_v2.types.Tool.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, Dialogflow 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["Tool.TLSConfig.CACert"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Tool.TLSConfig.CACert", + ) + + class ServiceDirectoryConfig(proto.Message): + r"""Configuration for tools using Service Directory. + + Attributes: + service (str): + Required. The name of `Service + Directory `__ + service. Format: + ``projects//locations//namespaces//services/``. + ``LocationID`` of the service directory must be the same as + the location of the tool. + """ + + service: str = proto.Field( + proto.STRING, + number=1, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + tool_key: str = proto.Field( + proto.STRING, + number=2, + ) + display_name: str = proto.Field( + proto.STRING, + number=19, + ) + description: str = proto.Field( + proto.STRING, + number=3, + ) + action_confirmation_requirement: MutableMapping[ + str, ConfirmationRequirement + ] = proto.MapField( + proto.STRING, + proto.ENUM, + number=17, + enum=ConfirmationRequirement, + ) + extension_spec: ExtensionTool = proto.Field( + proto.MESSAGE, + number=4, + oneof="specification", + message=ExtensionTool, + ) + function_spec: FunctionTool = proto.Field( + proto.MESSAGE, + number=13, + oneof="specification", + message=FunctionTool, + ) + connector_spec: ConnectorTool = proto.Field( + proto.MESSAGE, + number=18, + oneof="specification", + message=ConnectorTool, + ) + open_api_spec: OpenApiTool = proto.Field( + proto.MESSAGE, + number=20, + oneof="specification", + message=OpenApiTool, + ) + 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, + ) + satisfies_pzs: bool = proto.Field( + proto.BOOL, + number=14, + optional=True, + ) + satisfies_pzi: bool = proto.Field( + proto.BOOL, + number=15, + optional=True, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/tool_call.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/tool_call.py new file mode 100644 index 000000000000..e07821f87277 --- /dev/null +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2/types/tool_call.py @@ -0,0 +1,213 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.dialogflow.v2", + manifest={ + "ToolCall", + "ToolCallResult", + }, +) + + +class ToolCall(proto.Message): + r"""Represents a call of a specific tool's action with the + specified inputs. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + tool (str): + Optional. The [tool][google.cloud.dialogflow.v2.Tool] + associated with this call. Format: + ``projects//locations//tools/``. + + This field is a member of `oneof`_ ``source``. + tool_display_name (str): + Optional. A human readable short name of the + tool, to be shown on the UI. + tool_display_details (str): + Optional. A human readable description of the + tool. + action (str): + Optional. The name of the tool's action + associated with this call. + input_parameters (google.protobuf.struct_pb2.Struct): + Optional. The action's input parameters. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Create time of the tool call. + answer_record (str): + Optional. The answer record associated with + this tool call. + state (google.cloud.dialogflow_v2.types.ToolCall.State): + Output only. State of the tool call. + """ + + class State(proto.Enum): + r"""Tool call states. + + Values: + STATE_UNSPECIFIED (0): + Default value. + TRIGGERED (1): + The tool call has been triggered. + NEEDS_CONFIRMATION (2): + The tool call requires confirmation from a + human. + """ + STATE_UNSPECIFIED = 0 + TRIGGERED = 1 + NEEDS_CONFIRMATION = 2 + + tool: str = proto.Field( + proto.STRING, + number=1, + oneof="source", + ) + tool_display_name: str = proto.Field( + proto.STRING, + number=9, + ) + tool_display_details: str = proto.Field( + proto.STRING, + number=10, + ) + action: str = proto.Field( + proto.STRING, + number=2, + ) + input_parameters: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=3, + message=struct_pb2.Struct, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + answer_record: str = proto.Field( + proto.STRING, + number=6, + ) + state: State = proto.Field( + proto.ENUM, + number=7, + enum=State, + ) + + +class ToolCallResult(proto.Message): + r"""The result of calling a tool's action. + + 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 [tool][google.cloud.dialogflow.v2.Tool] + associated with this call. Format: + ``projects//locations//tools/``. + + This field is a member of `oneof`_ ``source``. + action (str): + Optional. The name of the tool's action + associated with this call. + error (google.cloud.dialogflow_v2.types.ToolCallResult.Error): + The tool call's error. + + This field is a member of `oneof`_ ``result``. + raw_content (bytes): + Only populated if the response content is not + utf-8 encoded. (by definition byte fields are + base64 encoded). + + This field is a member of `oneof`_ ``result``. + content (str): + Only populated if the response content is + utf-8 encoded. + + This field is a member of `oneof`_ ``result``. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Create time of the tool call + result. + answer_record (str): + Optional. The answer record associated with + this tool call result. + """ + + class Error(proto.Message): + r"""An error produced by the tool call. + + Attributes: + message (str): + Optional. The error message of the function. + """ + + message: str = proto.Field( + proto.STRING, + number=1, + ) + + tool: str = proto.Field( + proto.STRING, + number=1, + oneof="source", + ) + action: str = proto.Field( + proto.STRING, + number=2, + ) + error: Error = proto.Field( + proto.MESSAGE, + number=3, + oneof="result", + message=Error, + ) + raw_content: bytes = proto.Field( + proto.BYTES, + number=5, + oneof="result", + ) + content: str = proto.Field( + proto.STRING, + number=6, + oneof="result", + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + answer_record: str = proto.Field( + proto.STRING, + number=9, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/types/agent_coaching_instruction.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/types/agent_coaching_instruction.py index 5a62c8db72d1..40969c30cac5 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/types/agent_coaching_instruction.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/types/agent_coaching_instruction.py @@ -55,8 +55,38 @@ class AgentCoachingInstruction(proto.Message): duplicate_check_result (google.cloud.dialogflow_v2beta1.types.AgentCoachingInstruction.DuplicateCheckResult): Output only. Duplication check for the AgentCoachingInstruction. + triggering_event (google.cloud.dialogflow_v2beta1.types.AgentCoachingInstruction.TriggerEvent): + Optional. The event that should trigger this instruction. If + UNSPECIFIED, the instruction triggering will be same as the + generator's trigger_event. """ + class TriggerEvent(proto.Enum): + r"""The event that should trigger this instruction. + + Values: + TRIGGER_EVENT_UNSPECIFIED (0): + Default value for TriggerEvent. + END_OF_UTTERANCE (1): + Triggers when each chat message or voice + utterance ends. + MANUAL_CALL (2): + Triggers on the conversation manually by API + calls. + CUSTOMER_MESSAGE (3): + Triggers after each customer message. + AGENT_MESSAGE (4): + Triggers after each agent message. + TOOL_CALL_COMPLETION (5): + Triggers on tool call completion. + """ + TRIGGER_EVENT_UNSPECIFIED = 0 + END_OF_UTTERANCE = 1 + MANUAL_CALL = 2 + CUSTOMER_MESSAGE = 3 + AGENT_MESSAGE = 4 + TOOL_CALL_COMPLETION = 5 + class DuplicateCheckResult(proto.Message): r"""Duplication check for the suggestion. @@ -126,6 +156,11 @@ class DuplicateSuggestion(proto.Message): number=8, message=DuplicateCheckResult, ) + triggering_event: TriggerEvent = proto.Field( + proto.ENUM, + number=10, + enum=TriggerEvent, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_generator_evaluations_create_generator_evaluation_async.py b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_generator_evaluations_create_generator_evaluation_async.py new file mode 100644 index 000000000000..9df52b4aa879 --- /dev/null +++ b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_generator_evaluations_create_generator_evaluation_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 CreateGeneratorEvaluation +# 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-dialogflow + + +# [START dialogflow_v2_generated_GeneratorEvaluations_CreateGeneratorEvaluation_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 dialogflow_v2 + + +async def sample_create_generator_evaluation(): + # Create a client + client = dialogflow_v2.GeneratorEvaluationsAsyncClient() + + # Initialize request argument(s) + generator_evaluation = dialogflow_v2.GeneratorEvaluation() + generator_evaluation.generator_evaluation_config.input_data_config.input_data_source_type = ( + "INSIGHTS_CONVERSATIONS" + ) + generator_evaluation.generator_evaluation_config.output_gcs_bucket_path = ( + "output_gcs_bucket_path_value" + ) + generator_evaluation.initial_generator.published_model = "published_model_value" + + request = dialogflow_v2.CreateGeneratorEvaluationRequest( + parent="parent_value", + generator_evaluation=generator_evaluation, + ) + + # Make the request + operation = client.create_generator_evaluation(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + +# [END dialogflow_v2_generated_GeneratorEvaluations_CreateGeneratorEvaluation_async] diff --git a/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_generator_evaluations_create_generator_evaluation_sync.py b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_generator_evaluations_create_generator_evaluation_sync.py new file mode 100644 index 000000000000..f19dfe565d43 --- /dev/null +++ b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_generator_evaluations_create_generator_evaluation_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 CreateGeneratorEvaluation +# 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-dialogflow + + +# [START dialogflow_v2_generated_GeneratorEvaluations_CreateGeneratorEvaluation_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 dialogflow_v2 + + +def sample_create_generator_evaluation(): + # Create a client + client = dialogflow_v2.GeneratorEvaluationsClient() + + # Initialize request argument(s) + generator_evaluation = dialogflow_v2.GeneratorEvaluation() + generator_evaluation.generator_evaluation_config.input_data_config.input_data_source_type = ( + "INSIGHTS_CONVERSATIONS" + ) + generator_evaluation.generator_evaluation_config.output_gcs_bucket_path = ( + "output_gcs_bucket_path_value" + ) + generator_evaluation.initial_generator.published_model = "published_model_value" + + request = dialogflow_v2.CreateGeneratorEvaluationRequest( + parent="parent_value", + generator_evaluation=generator_evaluation, + ) + + # Make the request + operation = client.create_generator_evaluation(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END dialogflow_v2_generated_GeneratorEvaluations_CreateGeneratorEvaluation_sync] diff --git a/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_generator_evaluations_delete_generator_evaluation_async.py b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_generator_evaluations_delete_generator_evaluation_async.py new file mode 100644 index 000000000000..91e396caa1bd --- /dev/null +++ b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_generator_evaluations_delete_generator_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 DeleteGeneratorEvaluation +# 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-dialogflow + + +# [START dialogflow_v2_generated_GeneratorEvaluations_DeleteGeneratorEvaluation_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 dialogflow_v2 + + +async def sample_delete_generator_evaluation(): + # Create a client + client = dialogflow_v2.GeneratorEvaluationsAsyncClient() + + # Initialize request argument(s) + request = dialogflow_v2.DeleteGeneratorEvaluationRequest( + name="name_value", + ) + + # Make the request + await client.delete_generator_evaluation(request=request) + + +# [END dialogflow_v2_generated_GeneratorEvaluations_DeleteGeneratorEvaluation_async] diff --git a/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_generator_evaluations_delete_generator_evaluation_sync.py b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_generator_evaluations_delete_generator_evaluation_sync.py new file mode 100644 index 000000000000..1c3f1b4df40a --- /dev/null +++ b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_generator_evaluations_delete_generator_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 DeleteGeneratorEvaluation +# 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-dialogflow + + +# [START dialogflow_v2_generated_GeneratorEvaluations_DeleteGeneratorEvaluation_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 dialogflow_v2 + + +def sample_delete_generator_evaluation(): + # Create a client + client = dialogflow_v2.GeneratorEvaluationsClient() + + # Initialize request argument(s) + request = dialogflow_v2.DeleteGeneratorEvaluationRequest( + name="name_value", + ) + + # Make the request + client.delete_generator_evaluation(request=request) + + +# [END dialogflow_v2_generated_GeneratorEvaluations_DeleteGeneratorEvaluation_sync] diff --git a/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_generator_evaluations_get_generator_evaluation_async.py b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_generator_evaluations_get_generator_evaluation_async.py new file mode 100644 index 000000000000..fd2411070b79 --- /dev/null +++ b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_generator_evaluations_get_generator_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 GetGeneratorEvaluation +# 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-dialogflow + + +# [START dialogflow_v2_generated_GeneratorEvaluations_GetGeneratorEvaluation_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 dialogflow_v2 + + +async def sample_get_generator_evaluation(): + # Create a client + client = dialogflow_v2.GeneratorEvaluationsAsyncClient() + + # Initialize request argument(s) + request = dialogflow_v2.GetGeneratorEvaluationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_generator_evaluation(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v2_generated_GeneratorEvaluations_GetGeneratorEvaluation_async] diff --git a/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_generator_evaluations_get_generator_evaluation_sync.py b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_generator_evaluations_get_generator_evaluation_sync.py new file mode 100644 index 000000000000..86a6dbba238c --- /dev/null +++ b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_generator_evaluations_get_generator_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 GetGeneratorEvaluation +# 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-dialogflow + + +# [START dialogflow_v2_generated_GeneratorEvaluations_GetGeneratorEvaluation_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 dialogflow_v2 + + +def sample_get_generator_evaluation(): + # Create a client + client = dialogflow_v2.GeneratorEvaluationsClient() + + # Initialize request argument(s) + request = dialogflow_v2.GetGeneratorEvaluationRequest( + name="name_value", + ) + + # Make the request + response = client.get_generator_evaluation(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v2_generated_GeneratorEvaluations_GetGeneratorEvaluation_sync] diff --git a/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_generator_evaluations_list_generator_evaluations_async.py b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_generator_evaluations_list_generator_evaluations_async.py new file mode 100644 index 000000000000..30e27ba00d68 --- /dev/null +++ b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_generator_evaluations_list_generator_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 ListGeneratorEvaluations +# 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-dialogflow + + +# [START dialogflow_v2_generated_GeneratorEvaluations_ListGeneratorEvaluations_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 dialogflow_v2 + + +async def sample_list_generator_evaluations(): + # Create a client + client = dialogflow_v2.GeneratorEvaluationsAsyncClient() + + # Initialize request argument(s) + request = dialogflow_v2.ListGeneratorEvaluationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_generator_evaluations(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END dialogflow_v2_generated_GeneratorEvaluations_ListGeneratorEvaluations_async] diff --git a/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_generator_evaluations_list_generator_evaluations_sync.py b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_generator_evaluations_list_generator_evaluations_sync.py new file mode 100644 index 000000000000..a91d7897b118 --- /dev/null +++ b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_generator_evaluations_list_generator_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 ListGeneratorEvaluations +# 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-dialogflow + + +# [START dialogflow_v2_generated_GeneratorEvaluations_ListGeneratorEvaluations_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 dialogflow_v2 + + +def sample_list_generator_evaluations(): + # Create a client + client = dialogflow_v2.GeneratorEvaluationsClient() + + # Initialize request argument(s) + request = dialogflow_v2.ListGeneratorEvaluationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_generator_evaluations(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END dialogflow_v2_generated_GeneratorEvaluations_ListGeneratorEvaluations_sync] diff --git a/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_sip_trunks_create_sip_trunk_async.py b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_sip_trunks_create_sip_trunk_async.py new file mode 100644 index 000000000000..4c5fb55c1b27 --- /dev/null +++ b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_sip_trunks_create_sip_trunk_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 CreateSipTrunk +# 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-dialogflow + + +# [START dialogflow_v2_generated_SipTrunks_CreateSipTrunk_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 dialogflow_v2 + + +async def sample_create_sip_trunk(): + # Create a client + client = dialogflow_v2.SipTrunksAsyncClient() + + # Initialize request argument(s) + sip_trunk = dialogflow_v2.SipTrunk() + sip_trunk.expected_hostname = [ + "expected_hostname_value1", + "expected_hostname_value2", + ] + + request = dialogflow_v2.CreateSipTrunkRequest( + parent="parent_value", + sip_trunk=sip_trunk, + ) + + # Make the request + response = await client.create_sip_trunk(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v2_generated_SipTrunks_CreateSipTrunk_async] diff --git a/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_sip_trunks_create_sip_trunk_sync.py b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_sip_trunks_create_sip_trunk_sync.py new file mode 100644 index 000000000000..f8aad6623cae --- /dev/null +++ b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_sip_trunks_create_sip_trunk_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 CreateSipTrunk +# 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-dialogflow + + +# [START dialogflow_v2_generated_SipTrunks_CreateSipTrunk_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 dialogflow_v2 + + +def sample_create_sip_trunk(): + # Create a client + client = dialogflow_v2.SipTrunksClient() + + # Initialize request argument(s) + sip_trunk = dialogflow_v2.SipTrunk() + sip_trunk.expected_hostname = [ + "expected_hostname_value1", + "expected_hostname_value2", + ] + + request = dialogflow_v2.CreateSipTrunkRequest( + parent="parent_value", + sip_trunk=sip_trunk, + ) + + # Make the request + response = client.create_sip_trunk(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v2_generated_SipTrunks_CreateSipTrunk_sync] diff --git a/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_sip_trunks_delete_sip_trunk_async.py b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_sip_trunks_delete_sip_trunk_async.py new file mode 100644 index 000000000000..79583746a3e4 --- /dev/null +++ b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_sip_trunks_delete_sip_trunk_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 DeleteSipTrunk +# 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-dialogflow + + +# [START dialogflow_v2_generated_SipTrunks_DeleteSipTrunk_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 dialogflow_v2 + + +async def sample_delete_sip_trunk(): + # Create a client + client = dialogflow_v2.SipTrunksAsyncClient() + + # Initialize request argument(s) + request = dialogflow_v2.DeleteSipTrunkRequest( + name="name_value", + ) + + # Make the request + await client.delete_sip_trunk(request=request) + + +# [END dialogflow_v2_generated_SipTrunks_DeleteSipTrunk_async] diff --git a/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_sip_trunks_delete_sip_trunk_sync.py b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_sip_trunks_delete_sip_trunk_sync.py new file mode 100644 index 000000000000..5a81552ba92a --- /dev/null +++ b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_sip_trunks_delete_sip_trunk_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 DeleteSipTrunk +# 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-dialogflow + + +# [START dialogflow_v2_generated_SipTrunks_DeleteSipTrunk_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 dialogflow_v2 + + +def sample_delete_sip_trunk(): + # Create a client + client = dialogflow_v2.SipTrunksClient() + + # Initialize request argument(s) + request = dialogflow_v2.DeleteSipTrunkRequest( + name="name_value", + ) + + # Make the request + client.delete_sip_trunk(request=request) + + +# [END dialogflow_v2_generated_SipTrunks_DeleteSipTrunk_sync] diff --git a/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_sip_trunks_get_sip_trunk_async.py b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_sip_trunks_get_sip_trunk_async.py new file mode 100644 index 000000000000..1f36190bbe52 --- /dev/null +++ b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_sip_trunks_get_sip_trunk_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 GetSipTrunk +# 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-dialogflow + + +# [START dialogflow_v2_generated_SipTrunks_GetSipTrunk_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 dialogflow_v2 + + +async def sample_get_sip_trunk(): + # Create a client + client = dialogflow_v2.SipTrunksAsyncClient() + + # Initialize request argument(s) + request = dialogflow_v2.GetSipTrunkRequest( + name="name_value", + ) + + # Make the request + response = await client.get_sip_trunk(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v2_generated_SipTrunks_GetSipTrunk_async] diff --git a/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_sip_trunks_get_sip_trunk_sync.py b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_sip_trunks_get_sip_trunk_sync.py new file mode 100644 index 000000000000..383b65eb11b3 --- /dev/null +++ b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_sip_trunks_get_sip_trunk_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 GetSipTrunk +# 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-dialogflow + + +# [START dialogflow_v2_generated_SipTrunks_GetSipTrunk_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 dialogflow_v2 + + +def sample_get_sip_trunk(): + # Create a client + client = dialogflow_v2.SipTrunksClient() + + # Initialize request argument(s) + request = dialogflow_v2.GetSipTrunkRequest( + name="name_value", + ) + + # Make the request + response = client.get_sip_trunk(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v2_generated_SipTrunks_GetSipTrunk_sync] diff --git a/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_sip_trunks_list_sip_trunks_async.py b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_sip_trunks_list_sip_trunks_async.py new file mode 100644 index 000000000000..ea1f86878601 --- /dev/null +++ b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_sip_trunks_list_sip_trunks_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 ListSipTrunks +# 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-dialogflow + + +# [START dialogflow_v2_generated_SipTrunks_ListSipTrunks_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 dialogflow_v2 + + +async def sample_list_sip_trunks(): + # Create a client + client = dialogflow_v2.SipTrunksAsyncClient() + + # Initialize request argument(s) + request = dialogflow_v2.ListSipTrunksRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sip_trunks(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END dialogflow_v2_generated_SipTrunks_ListSipTrunks_async] diff --git a/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_sip_trunks_list_sip_trunks_sync.py b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_sip_trunks_list_sip_trunks_sync.py new file mode 100644 index 000000000000..4124f902e335 --- /dev/null +++ b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_sip_trunks_list_sip_trunks_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 ListSipTrunks +# 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-dialogflow + + +# [START dialogflow_v2_generated_SipTrunks_ListSipTrunks_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 dialogflow_v2 + + +def sample_list_sip_trunks(): + # Create a client + client = dialogflow_v2.SipTrunksClient() + + # Initialize request argument(s) + request = dialogflow_v2.ListSipTrunksRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_sip_trunks(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END dialogflow_v2_generated_SipTrunks_ListSipTrunks_sync] diff --git a/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_sip_trunks_update_sip_trunk_async.py b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_sip_trunks_update_sip_trunk_async.py new file mode 100644 index 000000000000..02896651c1c1 --- /dev/null +++ b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_sip_trunks_update_sip_trunk_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 UpdateSipTrunk +# 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-dialogflow + + +# [START dialogflow_v2_generated_SipTrunks_UpdateSipTrunk_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 dialogflow_v2 + + +async def sample_update_sip_trunk(): + # Create a client + client = dialogflow_v2.SipTrunksAsyncClient() + + # Initialize request argument(s) + sip_trunk = dialogflow_v2.SipTrunk() + sip_trunk.expected_hostname = [ + "expected_hostname_value1", + "expected_hostname_value2", + ] + + request = dialogflow_v2.UpdateSipTrunkRequest( + sip_trunk=sip_trunk, + ) + + # Make the request + response = await client.update_sip_trunk(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v2_generated_SipTrunks_UpdateSipTrunk_async] diff --git a/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_sip_trunks_update_sip_trunk_sync.py b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_sip_trunks_update_sip_trunk_sync.py new file mode 100644 index 000000000000..9c72e660fe7b --- /dev/null +++ b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_sip_trunks_update_sip_trunk_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 UpdateSipTrunk +# 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-dialogflow + + +# [START dialogflow_v2_generated_SipTrunks_UpdateSipTrunk_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 dialogflow_v2 + + +def sample_update_sip_trunk(): + # Create a client + client = dialogflow_v2.SipTrunksClient() + + # Initialize request argument(s) + sip_trunk = dialogflow_v2.SipTrunk() + sip_trunk.expected_hostname = [ + "expected_hostname_value1", + "expected_hostname_value2", + ] + + request = dialogflow_v2.UpdateSipTrunkRequest( + sip_trunk=sip_trunk, + ) + + # Make the request + response = client.update_sip_trunk(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v2_generated_SipTrunks_UpdateSipTrunk_sync] diff --git a/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_tools_create_tool_async.py b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_tools_create_tool_async.py new file mode 100644 index 000000000000..cd7792a40a8c --- /dev/null +++ b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_tools_create_tool_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 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-dialogflow + + +# [START dialogflow_v2_generated_Tools_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 dialogflow_v2 + + +async def sample_create_tool(): + # Create a client + client = dialogflow_v2.ToolsAsyncClient() + + # Initialize request argument(s) + tool = dialogflow_v2.Tool() + tool.extension_spec.name = "name_value" + tool.tool_key = "tool_key_value" + + request = dialogflow_v2.CreateToolRequest( + parent="parent_value", + tool=tool, + ) + + # Make the request + response = await client.create_tool(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v2_generated_Tools_CreateTool_async] diff --git a/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_tools_create_tool_sync.py b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_tools_create_tool_sync.py new file mode 100644 index 000000000000..0922b8f067d2 --- /dev/null +++ b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_tools_create_tool_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 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-dialogflow + + +# [START dialogflow_v2_generated_Tools_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 dialogflow_v2 + + +def sample_create_tool(): + # Create a client + client = dialogflow_v2.ToolsClient() + + # Initialize request argument(s) + tool = dialogflow_v2.Tool() + tool.extension_spec.name = "name_value" + tool.tool_key = "tool_key_value" + + request = dialogflow_v2.CreateToolRequest( + parent="parent_value", + tool=tool, + ) + + # Make the request + response = client.create_tool(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v2_generated_Tools_CreateTool_sync] diff --git a/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_tools_delete_tool_async.py b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_tools_delete_tool_async.py new file mode 100644 index 000000000000..e9acefec26ad --- /dev/null +++ b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_tools_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-dialogflow + + +# [START dialogflow_v2_generated_Tools_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 dialogflow_v2 + + +async def sample_delete_tool(): + # Create a client + client = dialogflow_v2.ToolsAsyncClient() + + # Initialize request argument(s) + request = dialogflow_v2.DeleteToolRequest( + name="name_value", + ) + + # Make the request + await client.delete_tool(request=request) + + +# [END dialogflow_v2_generated_Tools_DeleteTool_async] diff --git a/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_tools_delete_tool_sync.py b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_tools_delete_tool_sync.py new file mode 100644 index 000000000000..fa9cc64f6f6e --- /dev/null +++ b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_tools_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-dialogflow + + +# [START dialogflow_v2_generated_Tools_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 dialogflow_v2 + + +def sample_delete_tool(): + # Create a client + client = dialogflow_v2.ToolsClient() + + # Initialize request argument(s) + request = dialogflow_v2.DeleteToolRequest( + name="name_value", + ) + + # Make the request + client.delete_tool(request=request) + + +# [END dialogflow_v2_generated_Tools_DeleteTool_sync] diff --git a/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_tools_get_tool_async.py b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_tools_get_tool_async.py new file mode 100644 index 000000000000..dc7535ca2f73 --- /dev/null +++ b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_tools_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-dialogflow + + +# [START dialogflow_v2_generated_Tools_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 dialogflow_v2 + + +async def sample_get_tool(): + # Create a client + client = dialogflow_v2.ToolsAsyncClient() + + # Initialize request argument(s) + request = dialogflow_v2.GetToolRequest( + name="name_value", + ) + + # Make the request + response = await client.get_tool(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v2_generated_Tools_GetTool_async] diff --git a/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_tools_get_tool_sync.py b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_tools_get_tool_sync.py new file mode 100644 index 000000000000..2f1c6eb3617b --- /dev/null +++ b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_tools_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-dialogflow + + +# [START dialogflow_v2_generated_Tools_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 dialogflow_v2 + + +def sample_get_tool(): + # Create a client + client = dialogflow_v2.ToolsClient() + + # Initialize request argument(s) + request = dialogflow_v2.GetToolRequest( + name="name_value", + ) + + # Make the request + response = client.get_tool(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v2_generated_Tools_GetTool_sync] diff --git a/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_tools_list_tools_async.py b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_tools_list_tools_async.py new file mode 100644 index 000000000000..24529991b4f3 --- /dev/null +++ b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_tools_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-dialogflow + + +# [START dialogflow_v2_generated_Tools_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 dialogflow_v2 + + +async def sample_list_tools(): + # Create a client + client = dialogflow_v2.ToolsAsyncClient() + + # Initialize request argument(s) + request = dialogflow_v2.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 dialogflow_v2_generated_Tools_ListTools_async] diff --git a/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_tools_list_tools_sync.py b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_tools_list_tools_sync.py new file mode 100644 index 000000000000..67ed04c3a3a3 --- /dev/null +++ b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_tools_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-dialogflow + + +# [START dialogflow_v2_generated_Tools_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 dialogflow_v2 + + +def sample_list_tools(): + # Create a client + client = dialogflow_v2.ToolsClient() + + # Initialize request argument(s) + request = dialogflow_v2.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 dialogflow_v2_generated_Tools_ListTools_sync] diff --git a/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_tools_update_tool_async.py b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_tools_update_tool_async.py new file mode 100644 index 000000000000..c28811bd3a36 --- /dev/null +++ b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_tools_update_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 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-dialogflow + + +# [START dialogflow_v2_generated_Tools_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 dialogflow_v2 + + +async def sample_update_tool(): + # Create a client + client = dialogflow_v2.ToolsAsyncClient() + + # Initialize request argument(s) + tool = dialogflow_v2.Tool() + tool.extension_spec.name = "name_value" + tool.tool_key = "tool_key_value" + + request = dialogflow_v2.UpdateToolRequest( + tool=tool, + ) + + # Make the request + response = await client.update_tool(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v2_generated_Tools_UpdateTool_async] diff --git a/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_tools_update_tool_sync.py b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_tools_update_tool_sync.py new file mode 100644 index 000000000000..5f6859689c2e --- /dev/null +++ b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2_generated_tools_update_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 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-dialogflow + + +# [START dialogflow_v2_generated_Tools_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 dialogflow_v2 + + +def sample_update_tool(): + # Create a client + client = dialogflow_v2.ToolsClient() + + # Initialize request argument(s) + tool = dialogflow_v2.Tool() + tool.extension_spec.name = "name_value" + tool.tool_key = "tool_key_value" + + request = dialogflow_v2.UpdateToolRequest( + tool=tool, + ) + + # Make the request + response = client.update_tool(request=request) + + # Handle the response + print(response) + + +# [END dialogflow_v2_generated_Tools_UpdateTool_sync] diff --git a/packages/google-cloud-dialogflow/samples/generated_samples/snippet_metadata_google.cloud.dialogflow.v2.json b/packages/google-cloud-dialogflow/samples/generated_samples/snippet_metadata_google.cloud.dialogflow.v2.json index 2a138321922f..ad12cd3ba307 100644 --- a/packages/google-cloud-dialogflow/samples/generated_samples/snippet_metadata_google.cloud.dialogflow.v2.json +++ b/packages/google-cloud-dialogflow/samples/generated_samples/snippet_metadata_google.cloud.dialogflow.v2.json @@ -12481,34 +12481,30 @@ "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflow_v2.GeneratorsAsyncClient", - "shortName": "GeneratorsAsyncClient" + "fullName": "google.cloud.dialogflow_v2.GeneratorEvaluationsAsyncClient", + "shortName": "GeneratorEvaluationsAsyncClient" }, - "fullName": "google.cloud.dialogflow_v2.GeneratorsAsyncClient.create_generator", + "fullName": "google.cloud.dialogflow_v2.GeneratorEvaluationsAsyncClient.create_generator_evaluation", "method": { - "fullName": "google.cloud.dialogflow.v2.Generators.CreateGenerator", + "fullName": "google.cloud.dialogflow.v2.GeneratorEvaluations.CreateGeneratorEvaluation", "service": { - "fullName": "google.cloud.dialogflow.v2.Generators", - "shortName": "Generators" + "fullName": "google.cloud.dialogflow.v2.GeneratorEvaluations", + "shortName": "GeneratorEvaluations" }, - "shortName": "CreateGenerator" + "shortName": "CreateGeneratorEvaluation" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.CreateGeneratorRequest" + "type": "google.cloud.dialogflow_v2.types.CreateGeneratorEvaluationRequest" }, { "name": "parent", "type": "str" }, { - "name": "generator", - "type": "google.cloud.dialogflow_v2.types.Generator" - }, - { - "name": "generator_id", - "type": "str" + "name": "generator_evaluation", + "type": "google.cloud.dialogflow_v2.types.GeneratorEvaluation" }, { "name": "retry", @@ -12523,22 +12519,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.types.Generator", - "shortName": "create_generator" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_generator_evaluation" }, - "description": "Sample for CreateGenerator", - "file": "dialogflow_v2_generated_generators_create_generator_async.py", + "description": "Sample for CreateGeneratorEvaluation", + "file": "dialogflow_v2_generated_generator_evaluations_create_generator_evaluation_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Generators_CreateGenerator_async", + "regionTag": "dialogflow_v2_generated_GeneratorEvaluations_CreateGeneratorEvaluation_async", "segments": [ { - "end": 55, + "end": 61, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 61, "start": 27, "type": "SHORT" }, @@ -12548,55 +12544,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 58, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 62, + "start": 59, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_generators_create_generator_async.py" + "title": "dialogflow_v2_generated_generator_evaluations_create_generator_evaluation_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflow_v2.GeneratorsClient", - "shortName": "GeneratorsClient" + "fullName": "google.cloud.dialogflow_v2.GeneratorEvaluationsClient", + "shortName": "GeneratorEvaluationsClient" }, - "fullName": "google.cloud.dialogflow_v2.GeneratorsClient.create_generator", + "fullName": "google.cloud.dialogflow_v2.GeneratorEvaluationsClient.create_generator_evaluation", "method": { - "fullName": "google.cloud.dialogflow.v2.Generators.CreateGenerator", + "fullName": "google.cloud.dialogflow.v2.GeneratorEvaluations.CreateGeneratorEvaluation", "service": { - "fullName": "google.cloud.dialogflow.v2.Generators", - "shortName": "Generators" + "fullName": "google.cloud.dialogflow.v2.GeneratorEvaluations", + "shortName": "GeneratorEvaluations" }, - "shortName": "CreateGenerator" + "shortName": "CreateGeneratorEvaluation" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.CreateGeneratorRequest" + "type": "google.cloud.dialogflow_v2.types.CreateGeneratorEvaluationRequest" }, { "name": "parent", "type": "str" }, { - "name": "generator", - "type": "google.cloud.dialogflow_v2.types.Generator" - }, - { - "name": "generator_id", - "type": "str" + "name": "generator_evaluation", + "type": "google.cloud.dialogflow_v2.types.GeneratorEvaluation" }, { "name": "retry", @@ -12611,22 +12603,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.types.Generator", - "shortName": "create_generator" + "resultType": "google.api_core.operation.Operation", + "shortName": "create_generator_evaluation" }, - "description": "Sample for CreateGenerator", - "file": "dialogflow_v2_generated_generators_create_generator_sync.py", + "description": "Sample for CreateGeneratorEvaluation", + "file": "dialogflow_v2_generated_generator_evaluations_create_generator_evaluation_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Generators_CreateGenerator_sync", + "regionTag": "dialogflow_v2_generated_GeneratorEvaluations_CreateGeneratorEvaluation_sync", "segments": [ { - "end": 55, + "end": 61, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 61, "start": 27, "type": "SHORT" }, @@ -12636,44 +12628,44 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 58, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 62, + "start": 59, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_generators_create_generator_sync.py" + "title": "dialogflow_v2_generated_generator_evaluations_create_generator_evaluation_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflow_v2.GeneratorsAsyncClient", - "shortName": "GeneratorsAsyncClient" + "fullName": "google.cloud.dialogflow_v2.GeneratorEvaluationsAsyncClient", + "shortName": "GeneratorEvaluationsAsyncClient" }, - "fullName": "google.cloud.dialogflow_v2.GeneratorsAsyncClient.delete_generator", + "fullName": "google.cloud.dialogflow_v2.GeneratorEvaluationsAsyncClient.delete_generator_evaluation", "method": { - "fullName": "google.cloud.dialogflow.v2.Generators.DeleteGenerator", + "fullName": "google.cloud.dialogflow.v2.GeneratorEvaluations.DeleteGeneratorEvaluation", "service": { - "fullName": "google.cloud.dialogflow.v2.Generators", - "shortName": "Generators" + "fullName": "google.cloud.dialogflow.v2.GeneratorEvaluations", + "shortName": "GeneratorEvaluations" }, - "shortName": "DeleteGenerator" + "shortName": "DeleteGeneratorEvaluation" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.DeleteGeneratorRequest" + "type": "google.cloud.dialogflow_v2.types.DeleteGeneratorEvaluationRequest" }, { "name": "name", @@ -12692,13 +12684,13 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_generator" + "shortName": "delete_generator_evaluation" }, - "description": "Sample for DeleteGenerator", - "file": "dialogflow_v2_generated_generators_delete_generator_async.py", + "description": "Sample for DeleteGeneratorEvaluation", + "file": "dialogflow_v2_generated_generator_evaluations_delete_generator_evaluation_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Generators_DeleteGenerator_async", + "regionTag": "dialogflow_v2_generated_GeneratorEvaluations_DeleteGeneratorEvaluation_async", "segments": [ { "end": 49, @@ -12729,28 +12721,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_generators_delete_generator_async.py" + "title": "dialogflow_v2_generated_generator_evaluations_delete_generator_evaluation_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflow_v2.GeneratorsClient", - "shortName": "GeneratorsClient" + "fullName": "google.cloud.dialogflow_v2.GeneratorEvaluationsClient", + "shortName": "GeneratorEvaluationsClient" }, - "fullName": "google.cloud.dialogflow_v2.GeneratorsClient.delete_generator", + "fullName": "google.cloud.dialogflow_v2.GeneratorEvaluationsClient.delete_generator_evaluation", "method": { - "fullName": "google.cloud.dialogflow.v2.Generators.DeleteGenerator", + "fullName": "google.cloud.dialogflow.v2.GeneratorEvaluations.DeleteGeneratorEvaluation", "service": { - "fullName": "google.cloud.dialogflow.v2.Generators", - "shortName": "Generators" + "fullName": "google.cloud.dialogflow.v2.GeneratorEvaluations", + "shortName": "GeneratorEvaluations" }, - "shortName": "DeleteGenerator" + "shortName": "DeleteGeneratorEvaluation" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.DeleteGeneratorRequest" + "type": "google.cloud.dialogflow_v2.types.DeleteGeneratorEvaluationRequest" }, { "name": "name", @@ -12769,13 +12761,13 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_generator" + "shortName": "delete_generator_evaluation" }, - "description": "Sample for DeleteGenerator", - "file": "dialogflow_v2_generated_generators_delete_generator_sync.py", + "description": "Sample for DeleteGeneratorEvaluation", + "file": "dialogflow_v2_generated_generator_evaluations_delete_generator_evaluation_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Generators_DeleteGenerator_sync", + "regionTag": "dialogflow_v2_generated_GeneratorEvaluations_DeleteGeneratorEvaluation_sync", "segments": [ { "end": 49, @@ -12806,29 +12798,29 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_generators_delete_generator_sync.py" + "title": "dialogflow_v2_generated_generator_evaluations_delete_generator_evaluation_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflow_v2.GeneratorsAsyncClient", - "shortName": "GeneratorsAsyncClient" + "fullName": "google.cloud.dialogflow_v2.GeneratorEvaluationsAsyncClient", + "shortName": "GeneratorEvaluationsAsyncClient" }, - "fullName": "google.cloud.dialogflow_v2.GeneratorsAsyncClient.get_generator", + "fullName": "google.cloud.dialogflow_v2.GeneratorEvaluationsAsyncClient.get_generator_evaluation", "method": { - "fullName": "google.cloud.dialogflow.v2.Generators.GetGenerator", + "fullName": "google.cloud.dialogflow.v2.GeneratorEvaluations.GetGeneratorEvaluation", "service": { - "fullName": "google.cloud.dialogflow.v2.Generators", - "shortName": "Generators" + "fullName": "google.cloud.dialogflow.v2.GeneratorEvaluations", + "shortName": "GeneratorEvaluations" }, - "shortName": "GetGenerator" + "shortName": "GetGeneratorEvaluation" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetGeneratorRequest" + "type": "google.cloud.dialogflow_v2.types.GetGeneratorEvaluationRequest" }, { "name": "name", @@ -12847,14 +12839,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.types.Generator", - "shortName": "get_generator" + "resultType": "google.cloud.dialogflow_v2.types.GeneratorEvaluation", + "shortName": "get_generator_evaluation" }, - "description": "Sample for GetGenerator", - "file": "dialogflow_v2_generated_generators_get_generator_async.py", + "description": "Sample for GetGeneratorEvaluation", + "file": "dialogflow_v2_generated_generator_evaluations_get_generator_evaluation_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Generators_GetGenerator_async", + "regionTag": "dialogflow_v2_generated_GeneratorEvaluations_GetGeneratorEvaluation_async", "segments": [ { "end": 51, @@ -12887,28 +12879,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_generators_get_generator_async.py" + "title": "dialogflow_v2_generated_generator_evaluations_get_generator_evaluation_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflow_v2.GeneratorsClient", - "shortName": "GeneratorsClient" + "fullName": "google.cloud.dialogflow_v2.GeneratorEvaluationsClient", + "shortName": "GeneratorEvaluationsClient" }, - "fullName": "google.cloud.dialogflow_v2.GeneratorsClient.get_generator", + "fullName": "google.cloud.dialogflow_v2.GeneratorEvaluationsClient.get_generator_evaluation", "method": { - "fullName": "google.cloud.dialogflow.v2.Generators.GetGenerator", + "fullName": "google.cloud.dialogflow.v2.GeneratorEvaluations.GetGeneratorEvaluation", "service": { - "fullName": "google.cloud.dialogflow.v2.Generators", - "shortName": "Generators" + "fullName": "google.cloud.dialogflow.v2.GeneratorEvaluations", + "shortName": "GeneratorEvaluations" }, - "shortName": "GetGenerator" + "shortName": "GetGeneratorEvaluation" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetGeneratorRequest" + "type": "google.cloud.dialogflow_v2.types.GetGeneratorEvaluationRequest" }, { "name": "name", @@ -12927,14 +12919,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.types.Generator", - "shortName": "get_generator" + "resultType": "google.cloud.dialogflow_v2.types.GeneratorEvaluation", + "shortName": "get_generator_evaluation" }, - "description": "Sample for GetGenerator", - "file": "dialogflow_v2_generated_generators_get_generator_sync.py", + "description": "Sample for GetGeneratorEvaluation", + "file": "dialogflow_v2_generated_generator_evaluations_get_generator_evaluation_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Generators_GetGenerator_sync", + "regionTag": "dialogflow_v2_generated_GeneratorEvaluations_GetGeneratorEvaluation_sync", "segments": [ { "end": 51, @@ -12967,29 +12959,29 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_generators_get_generator_sync.py" + "title": "dialogflow_v2_generated_generator_evaluations_get_generator_evaluation_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflow_v2.GeneratorsAsyncClient", - "shortName": "GeneratorsAsyncClient" + "fullName": "google.cloud.dialogflow_v2.GeneratorEvaluationsAsyncClient", + "shortName": "GeneratorEvaluationsAsyncClient" }, - "fullName": "google.cloud.dialogflow_v2.GeneratorsAsyncClient.list_generators", + "fullName": "google.cloud.dialogflow_v2.GeneratorEvaluationsAsyncClient.list_generator_evaluations", "method": { - "fullName": "google.cloud.dialogflow.v2.Generators.ListGenerators", + "fullName": "google.cloud.dialogflow.v2.GeneratorEvaluations.ListGeneratorEvaluations", "service": { - "fullName": "google.cloud.dialogflow.v2.Generators", - "shortName": "Generators" + "fullName": "google.cloud.dialogflow.v2.GeneratorEvaluations", + "shortName": "GeneratorEvaluations" }, - "shortName": "ListGenerators" + "shortName": "ListGeneratorEvaluations" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListGeneratorsRequest" + "type": "google.cloud.dialogflow_v2.types.ListGeneratorEvaluationsRequest" }, { "name": "parent", @@ -13008,14 +13000,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.services.generators.pagers.ListGeneratorsAsyncPager", - "shortName": "list_generators" + "resultType": "google.cloud.dialogflow_v2.services.generator_evaluations.pagers.ListGeneratorEvaluationsAsyncPager", + "shortName": "list_generator_evaluations" }, - "description": "Sample for ListGenerators", - "file": "dialogflow_v2_generated_generators_list_generators_async.py", + "description": "Sample for ListGeneratorEvaluations", + "file": "dialogflow_v2_generated_generator_evaluations_list_generator_evaluations_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Generators_ListGenerators_async", + "regionTag": "dialogflow_v2_generated_GeneratorEvaluations_ListGeneratorEvaluations_async", "segments": [ { "end": 52, @@ -13048,28 +13040,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_generators_list_generators_async.py" + "title": "dialogflow_v2_generated_generator_evaluations_list_generator_evaluations_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflow_v2.GeneratorsClient", - "shortName": "GeneratorsClient" + "fullName": "google.cloud.dialogflow_v2.GeneratorEvaluationsClient", + "shortName": "GeneratorEvaluationsClient" }, - "fullName": "google.cloud.dialogflow_v2.GeneratorsClient.list_generators", + "fullName": "google.cloud.dialogflow_v2.GeneratorEvaluationsClient.list_generator_evaluations", "method": { - "fullName": "google.cloud.dialogflow.v2.Generators.ListGenerators", + "fullName": "google.cloud.dialogflow.v2.GeneratorEvaluations.ListGeneratorEvaluations", "service": { - "fullName": "google.cloud.dialogflow.v2.Generators", - "shortName": "Generators" + "fullName": "google.cloud.dialogflow.v2.GeneratorEvaluations", + "shortName": "GeneratorEvaluations" }, - "shortName": "ListGenerators" + "shortName": "ListGeneratorEvaluations" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListGeneratorsRequest" + "type": "google.cloud.dialogflow_v2.types.ListGeneratorEvaluationsRequest" }, { "name": "parent", @@ -13088,14 +13080,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.services.generators.pagers.ListGeneratorsPager", - "shortName": "list_generators" + "resultType": "google.cloud.dialogflow_v2.services.generator_evaluations.pagers.ListGeneratorEvaluationsPager", + "shortName": "list_generator_evaluations" }, - "description": "Sample for ListGenerators", - "file": "dialogflow_v2_generated_generators_list_generators_sync.py", + "description": "Sample for ListGeneratorEvaluations", + "file": "dialogflow_v2_generated_generator_evaluations_list_generator_evaluations_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Generators_ListGenerators_sync", + "regionTag": "dialogflow_v2_generated_GeneratorEvaluations_ListGeneratorEvaluations_sync", "segments": [ { "end": 52, @@ -13128,7 +13120,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_generators_list_generators_sync.py" + "title": "dialogflow_v2_generated_generator_evaluations_list_generator_evaluations_sync.py" }, { "canonical": true, @@ -13138,27 +13130,31 @@ "fullName": "google.cloud.dialogflow_v2.GeneratorsAsyncClient", "shortName": "GeneratorsAsyncClient" }, - "fullName": "google.cloud.dialogflow_v2.GeneratorsAsyncClient.update_generator", + "fullName": "google.cloud.dialogflow_v2.GeneratorsAsyncClient.create_generator", "method": { - "fullName": "google.cloud.dialogflow.v2.Generators.UpdateGenerator", + "fullName": "google.cloud.dialogflow.v2.Generators.CreateGenerator", "service": { "fullName": "google.cloud.dialogflow.v2.Generators", "shortName": "Generators" }, - "shortName": "UpdateGenerator" + "shortName": "CreateGenerator" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.UpdateGeneratorRequest" + "type": "google.cloud.dialogflow_v2.types.CreateGeneratorRequest" + }, + { + "name": "parent", + "type": "str" }, { "name": "generator", "type": "google.cloud.dialogflow_v2.types.Generator" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "generator_id", + "type": "str" }, { "name": "retry", @@ -13174,21 +13170,21 @@ } ], "resultType": "google.cloud.dialogflow_v2.types.Generator", - "shortName": "update_generator" + "shortName": "create_generator" }, - "description": "Sample for UpdateGenerator", - "file": "dialogflow_v2_generated_generators_update_generator_async.py", + "description": "Sample for CreateGenerator", + "file": "dialogflow_v2_generated_generators_create_generator_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Generators_UpdateGenerator_async", + "regionTag": "dialogflow_v2_generated_Generators_CreateGenerator_async", "segments": [ { - "end": 54, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 55, "start": 27, "type": "SHORT" }, @@ -13198,22 +13194,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 49, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_generators_update_generator_async.py" + "title": "dialogflow_v2_generated_generators_create_generator_async.py" }, { "canonical": true, @@ -13222,27 +13218,31 @@ "fullName": "google.cloud.dialogflow_v2.GeneratorsClient", "shortName": "GeneratorsClient" }, - "fullName": "google.cloud.dialogflow_v2.GeneratorsClient.update_generator", + "fullName": "google.cloud.dialogflow_v2.GeneratorsClient.create_generator", "method": { - "fullName": "google.cloud.dialogflow.v2.Generators.UpdateGenerator", + "fullName": "google.cloud.dialogflow.v2.Generators.CreateGenerator", "service": { "fullName": "google.cloud.dialogflow.v2.Generators", "shortName": "Generators" }, - "shortName": "UpdateGenerator" + "shortName": "CreateGenerator" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.UpdateGeneratorRequest" + "type": "google.cloud.dialogflow_v2.types.CreateGeneratorRequest" + }, + { + "name": "parent", + "type": "str" }, { "name": "generator", "type": "google.cloud.dialogflow_v2.types.Generator" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "generator_id", + "type": "str" }, { "name": "retry", @@ -13258,21 +13258,21 @@ } ], "resultType": "google.cloud.dialogflow_v2.types.Generator", - "shortName": "update_generator" + "shortName": "create_generator" }, - "description": "Sample for UpdateGenerator", - "file": "dialogflow_v2_generated_generators_update_generator_sync.py", + "description": "Sample for CreateGenerator", + "file": "dialogflow_v2_generated_generators_create_generator_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Generators_UpdateGenerator_sync", + "regionTag": "dialogflow_v2_generated_Generators_CreateGenerator_sync", "segments": [ { - "end": 54, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 55, "start": 27, "type": "SHORT" }, @@ -13282,53 +13282,49 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 49, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_generators_update_generator_sync.py" + "title": "dialogflow_v2_generated_generators_create_generator_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient", - "shortName": "IntentsAsyncClient" + "fullName": "google.cloud.dialogflow_v2.GeneratorsAsyncClient", + "shortName": "GeneratorsAsyncClient" }, - "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient.batch_delete_intents", + "fullName": "google.cloud.dialogflow_v2.GeneratorsAsyncClient.delete_generator", "method": { - "fullName": "google.cloud.dialogflow.v2.Intents.BatchDeleteIntents", + "fullName": "google.cloud.dialogflow.v2.Generators.DeleteGenerator", "service": { - "fullName": "google.cloud.dialogflow.v2.Intents", - "shortName": "Intents" + "fullName": "google.cloud.dialogflow.v2.Generators", + "shortName": "Generators" }, - "shortName": "BatchDeleteIntents" + "shortName": "DeleteGenerator" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.BatchDeleteIntentsRequest" + "type": "google.cloud.dialogflow_v2.types.DeleteGeneratorRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, - { - "name": "intents", - "type": "MutableSequence[google.cloud.dialogflow_v2.types.Intent]" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -13342,22 +13338,2346 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "batch_delete_intents" + "shortName": "delete_generator" + }, + "description": "Sample for DeleteGenerator", + "file": "dialogflow_v2_generated_generators_delete_generator_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v2_generated_Generators_DeleteGenerator_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": "dialogflow_v2_generated_generators_delete_generator_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflow_v2.GeneratorsClient", + "shortName": "GeneratorsClient" + }, + "fullName": "google.cloud.dialogflow_v2.GeneratorsClient.delete_generator", + "method": { + "fullName": "google.cloud.dialogflow.v2.Generators.DeleteGenerator", + "service": { + "fullName": "google.cloud.dialogflow.v2.Generators", + "shortName": "Generators" + }, + "shortName": "DeleteGenerator" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflow_v2.types.DeleteGeneratorRequest" + }, + { + "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_generator" + }, + "description": "Sample for DeleteGenerator", + "file": "dialogflow_v2_generated_generators_delete_generator_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v2_generated_Generators_DeleteGenerator_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": "dialogflow_v2_generated_generators_delete_generator_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflow_v2.GeneratorsAsyncClient", + "shortName": "GeneratorsAsyncClient" + }, + "fullName": "google.cloud.dialogflow_v2.GeneratorsAsyncClient.get_generator", + "method": { + "fullName": "google.cloud.dialogflow.v2.Generators.GetGenerator", + "service": { + "fullName": "google.cloud.dialogflow.v2.Generators", + "shortName": "Generators" + }, + "shortName": "GetGenerator" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflow_v2.types.GetGeneratorRequest" + }, + { + "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.dialogflow_v2.types.Generator", + "shortName": "get_generator" + }, + "description": "Sample for GetGenerator", + "file": "dialogflow_v2_generated_generators_get_generator_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v2_generated_Generators_GetGenerator_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": "dialogflow_v2_generated_generators_get_generator_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflow_v2.GeneratorsClient", + "shortName": "GeneratorsClient" + }, + "fullName": "google.cloud.dialogflow_v2.GeneratorsClient.get_generator", + "method": { + "fullName": "google.cloud.dialogflow.v2.Generators.GetGenerator", + "service": { + "fullName": "google.cloud.dialogflow.v2.Generators", + "shortName": "Generators" + }, + "shortName": "GetGenerator" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflow_v2.types.GetGeneratorRequest" + }, + { + "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.dialogflow_v2.types.Generator", + "shortName": "get_generator" + }, + "description": "Sample for GetGenerator", + "file": "dialogflow_v2_generated_generators_get_generator_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v2_generated_Generators_GetGenerator_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": "dialogflow_v2_generated_generators_get_generator_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflow_v2.GeneratorsAsyncClient", + "shortName": "GeneratorsAsyncClient" + }, + "fullName": "google.cloud.dialogflow_v2.GeneratorsAsyncClient.list_generators", + "method": { + "fullName": "google.cloud.dialogflow.v2.Generators.ListGenerators", + "service": { + "fullName": "google.cloud.dialogflow.v2.Generators", + "shortName": "Generators" + }, + "shortName": "ListGenerators" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflow_v2.types.ListGeneratorsRequest" + }, + { + "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.dialogflow_v2.services.generators.pagers.ListGeneratorsAsyncPager", + "shortName": "list_generators" + }, + "description": "Sample for ListGenerators", + "file": "dialogflow_v2_generated_generators_list_generators_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v2_generated_Generators_ListGenerators_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": "dialogflow_v2_generated_generators_list_generators_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflow_v2.GeneratorsClient", + "shortName": "GeneratorsClient" + }, + "fullName": "google.cloud.dialogflow_v2.GeneratorsClient.list_generators", + "method": { + "fullName": "google.cloud.dialogflow.v2.Generators.ListGenerators", + "service": { + "fullName": "google.cloud.dialogflow.v2.Generators", + "shortName": "Generators" + }, + "shortName": "ListGenerators" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflow_v2.types.ListGeneratorsRequest" + }, + { + "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.dialogflow_v2.services.generators.pagers.ListGeneratorsPager", + "shortName": "list_generators" + }, + "description": "Sample for ListGenerators", + "file": "dialogflow_v2_generated_generators_list_generators_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v2_generated_Generators_ListGenerators_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": "dialogflow_v2_generated_generators_list_generators_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflow_v2.GeneratorsAsyncClient", + "shortName": "GeneratorsAsyncClient" + }, + "fullName": "google.cloud.dialogflow_v2.GeneratorsAsyncClient.update_generator", + "method": { + "fullName": "google.cloud.dialogflow.v2.Generators.UpdateGenerator", + "service": { + "fullName": "google.cloud.dialogflow.v2.Generators", + "shortName": "Generators" + }, + "shortName": "UpdateGenerator" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflow_v2.types.UpdateGeneratorRequest" + }, + { + "name": "generator", + "type": "google.cloud.dialogflow_v2.types.Generator" + }, + { + "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.dialogflow_v2.types.Generator", + "shortName": "update_generator" + }, + "description": "Sample for UpdateGenerator", + "file": "dialogflow_v2_generated_generators_update_generator_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v2_generated_Generators_UpdateGenerator_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": "dialogflow_v2_generated_generators_update_generator_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflow_v2.GeneratorsClient", + "shortName": "GeneratorsClient" + }, + "fullName": "google.cloud.dialogflow_v2.GeneratorsClient.update_generator", + "method": { + "fullName": "google.cloud.dialogflow.v2.Generators.UpdateGenerator", + "service": { + "fullName": "google.cloud.dialogflow.v2.Generators", + "shortName": "Generators" + }, + "shortName": "UpdateGenerator" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflow_v2.types.UpdateGeneratorRequest" + }, + { + "name": "generator", + "type": "google.cloud.dialogflow_v2.types.Generator" + }, + { + "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.dialogflow_v2.types.Generator", + "shortName": "update_generator" + }, + "description": "Sample for UpdateGenerator", + "file": "dialogflow_v2_generated_generators_update_generator_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v2_generated_Generators_UpdateGenerator_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": "dialogflow_v2_generated_generators_update_generator_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient", + "shortName": "IntentsAsyncClient" + }, + "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient.batch_delete_intents", + "method": { + "fullName": "google.cloud.dialogflow.v2.Intents.BatchDeleteIntents", + "service": { + "fullName": "google.cloud.dialogflow.v2.Intents", + "shortName": "Intents" + }, + "shortName": "BatchDeleteIntents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflow_v2.types.BatchDeleteIntentsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "intents", + "type": "MutableSequence[google.cloud.dialogflow_v2.types.Intent]" + }, + { + "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_intents" + }, + "description": "Sample for BatchDeleteIntents", + "file": "dialogflow_v2_generated_intents_batch_delete_intents_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v2_generated_Intents_BatchDeleteIntents_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": "dialogflow_v2_generated_intents_batch_delete_intents_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflow_v2.IntentsClient", + "shortName": "IntentsClient" + }, + "fullName": "google.cloud.dialogflow_v2.IntentsClient.batch_delete_intents", + "method": { + "fullName": "google.cloud.dialogflow.v2.Intents.BatchDeleteIntents", + "service": { + "fullName": "google.cloud.dialogflow.v2.Intents", + "shortName": "Intents" + }, + "shortName": "BatchDeleteIntents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflow_v2.types.BatchDeleteIntentsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "intents", + "type": "MutableSequence[google.cloud.dialogflow_v2.types.Intent]" + }, + { + "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_intents" + }, + "description": "Sample for BatchDeleteIntents", + "file": "dialogflow_v2_generated_intents_batch_delete_intents_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v2_generated_Intents_BatchDeleteIntents_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": "dialogflow_v2_generated_intents_batch_delete_intents_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient", + "shortName": "IntentsAsyncClient" + }, + "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient.batch_update_intents", + "method": { + "fullName": "google.cloud.dialogflow.v2.Intents.BatchUpdateIntents", + "service": { + "fullName": "google.cloud.dialogflow.v2.Intents", + "shortName": "Intents" + }, + "shortName": "BatchUpdateIntents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflow_v2.types.BatchUpdateIntentsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "intent_batch_uri", + "type": "str" + }, + { + "name": "intent_batch_inline", + "type": "google.cloud.dialogflow_v2.types.IntentBatch" + }, + { + "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_update_intents" + }, + "description": "Sample for BatchUpdateIntents", + "file": "dialogflow_v2_generated_intents_batch_update_intents_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v2_generated_Intents_BatchUpdateIntents_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": "dialogflow_v2_generated_intents_batch_update_intents_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflow_v2.IntentsClient", + "shortName": "IntentsClient" + }, + "fullName": "google.cloud.dialogflow_v2.IntentsClient.batch_update_intents", + "method": { + "fullName": "google.cloud.dialogflow.v2.Intents.BatchUpdateIntents", + "service": { + "fullName": "google.cloud.dialogflow.v2.Intents", + "shortName": "Intents" + }, + "shortName": "BatchUpdateIntents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflow_v2.types.BatchUpdateIntentsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "intent_batch_uri", + "type": "str" + }, + { + "name": "intent_batch_inline", + "type": "google.cloud.dialogflow_v2.types.IntentBatch" + }, + { + "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_update_intents" + }, + "description": "Sample for BatchUpdateIntents", + "file": "dialogflow_v2_generated_intents_batch_update_intents_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v2_generated_Intents_BatchUpdateIntents_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": "dialogflow_v2_generated_intents_batch_update_intents_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient", + "shortName": "IntentsAsyncClient" + }, + "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient.create_intent", + "method": { + "fullName": "google.cloud.dialogflow.v2.Intents.CreateIntent", + "service": { + "fullName": "google.cloud.dialogflow.v2.Intents", + "shortName": "Intents" + }, + "shortName": "CreateIntent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflow_v2.types.CreateIntentRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "intent", + "type": "google.cloud.dialogflow_v2.types.Intent" + }, + { + "name": "language_code", + "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.dialogflow_v2.types.Intent", + "shortName": "create_intent" + }, + "description": "Sample for CreateIntent", + "file": "dialogflow_v2_generated_intents_create_intent_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v2_generated_Intents_CreateIntent_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": "dialogflow_v2_generated_intents_create_intent_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflow_v2.IntentsClient", + "shortName": "IntentsClient" + }, + "fullName": "google.cloud.dialogflow_v2.IntentsClient.create_intent", + "method": { + "fullName": "google.cloud.dialogflow.v2.Intents.CreateIntent", + "service": { + "fullName": "google.cloud.dialogflow.v2.Intents", + "shortName": "Intents" + }, + "shortName": "CreateIntent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflow_v2.types.CreateIntentRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "intent", + "type": "google.cloud.dialogflow_v2.types.Intent" + }, + { + "name": "language_code", + "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.dialogflow_v2.types.Intent", + "shortName": "create_intent" + }, + "description": "Sample for CreateIntent", + "file": "dialogflow_v2_generated_intents_create_intent_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v2_generated_Intents_CreateIntent_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": "dialogflow_v2_generated_intents_create_intent_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient", + "shortName": "IntentsAsyncClient" + }, + "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient.delete_intent", + "method": { + "fullName": "google.cloud.dialogflow.v2.Intents.DeleteIntent", + "service": { + "fullName": "google.cloud.dialogflow.v2.Intents", + "shortName": "Intents" + }, + "shortName": "DeleteIntent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflow_v2.types.DeleteIntentRequest" + }, + { + "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_intent" + }, + "description": "Sample for DeleteIntent", + "file": "dialogflow_v2_generated_intents_delete_intent_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v2_generated_Intents_DeleteIntent_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": "dialogflow_v2_generated_intents_delete_intent_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflow_v2.IntentsClient", + "shortName": "IntentsClient" + }, + "fullName": "google.cloud.dialogflow_v2.IntentsClient.delete_intent", + "method": { + "fullName": "google.cloud.dialogflow.v2.Intents.DeleteIntent", + "service": { + "fullName": "google.cloud.dialogflow.v2.Intents", + "shortName": "Intents" + }, + "shortName": "DeleteIntent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflow_v2.types.DeleteIntentRequest" + }, + { + "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_intent" + }, + "description": "Sample for DeleteIntent", + "file": "dialogflow_v2_generated_intents_delete_intent_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v2_generated_Intents_DeleteIntent_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": "dialogflow_v2_generated_intents_delete_intent_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient", + "shortName": "IntentsAsyncClient" + }, + "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient.get_intent", + "method": { + "fullName": "google.cloud.dialogflow.v2.Intents.GetIntent", + "service": { + "fullName": "google.cloud.dialogflow.v2.Intents", + "shortName": "Intents" + }, + "shortName": "GetIntent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflow_v2.types.GetIntentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "language_code", + "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.dialogflow_v2.types.Intent", + "shortName": "get_intent" + }, + "description": "Sample for GetIntent", + "file": "dialogflow_v2_generated_intents_get_intent_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v2_generated_Intents_GetIntent_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": "dialogflow_v2_generated_intents_get_intent_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflow_v2.IntentsClient", + "shortName": "IntentsClient" + }, + "fullName": "google.cloud.dialogflow_v2.IntentsClient.get_intent", + "method": { + "fullName": "google.cloud.dialogflow.v2.Intents.GetIntent", + "service": { + "fullName": "google.cloud.dialogflow.v2.Intents", + "shortName": "Intents" + }, + "shortName": "GetIntent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflow_v2.types.GetIntentRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "language_code", + "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.dialogflow_v2.types.Intent", + "shortName": "get_intent" + }, + "description": "Sample for GetIntent", + "file": "dialogflow_v2_generated_intents_get_intent_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v2_generated_Intents_GetIntent_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": "dialogflow_v2_generated_intents_get_intent_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient", + "shortName": "IntentsAsyncClient" + }, + "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient.list_intents", + "method": { + "fullName": "google.cloud.dialogflow.v2.Intents.ListIntents", + "service": { + "fullName": "google.cloud.dialogflow.v2.Intents", + "shortName": "Intents" + }, + "shortName": "ListIntents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflow_v2.types.ListIntentsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "language_code", + "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.dialogflow_v2.services.intents.pagers.ListIntentsAsyncPager", + "shortName": "list_intents" + }, + "description": "Sample for ListIntents", + "file": "dialogflow_v2_generated_intents_list_intents_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v2_generated_Intents_ListIntents_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": "dialogflow_v2_generated_intents_list_intents_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflow_v2.IntentsClient", + "shortName": "IntentsClient" + }, + "fullName": "google.cloud.dialogflow_v2.IntentsClient.list_intents", + "method": { + "fullName": "google.cloud.dialogflow.v2.Intents.ListIntents", + "service": { + "fullName": "google.cloud.dialogflow.v2.Intents", + "shortName": "Intents" + }, + "shortName": "ListIntents" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflow_v2.types.ListIntentsRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "language_code", + "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.dialogflow_v2.services.intents.pagers.ListIntentsPager", + "shortName": "list_intents" + }, + "description": "Sample for ListIntents", + "file": "dialogflow_v2_generated_intents_list_intents_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v2_generated_Intents_ListIntents_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": "dialogflow_v2_generated_intents_list_intents_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient", + "shortName": "IntentsAsyncClient" + }, + "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient.update_intent", + "method": { + "fullName": "google.cloud.dialogflow.v2.Intents.UpdateIntent", + "service": { + "fullName": "google.cloud.dialogflow.v2.Intents", + "shortName": "Intents" + }, + "shortName": "UpdateIntent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflow_v2.types.UpdateIntentRequest" + }, + { + "name": "intent", + "type": "google.cloud.dialogflow_v2.types.Intent" + }, + { + "name": "language_code", + "type": "str" + }, + { + "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.dialogflow_v2.types.Intent", + "shortName": "update_intent" + }, + "description": "Sample for UpdateIntent", + "file": "dialogflow_v2_generated_intents_update_intent_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v2_generated_Intents_UpdateIntent_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": "dialogflow_v2_generated_intents_update_intent_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflow_v2.IntentsClient", + "shortName": "IntentsClient" + }, + "fullName": "google.cloud.dialogflow_v2.IntentsClient.update_intent", + "method": { + "fullName": "google.cloud.dialogflow.v2.Intents.UpdateIntent", + "service": { + "fullName": "google.cloud.dialogflow.v2.Intents", + "shortName": "Intents" + }, + "shortName": "UpdateIntent" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflow_v2.types.UpdateIntentRequest" + }, + { + "name": "intent", + "type": "google.cloud.dialogflow_v2.types.Intent" + }, + { + "name": "language_code", + "type": "str" + }, + { + "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.dialogflow_v2.types.Intent", + "shortName": "update_intent" + }, + "description": "Sample for UpdateIntent", + "file": "dialogflow_v2_generated_intents_update_intent_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v2_generated_Intents_UpdateIntent_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": "dialogflow_v2_generated_intents_update_intent_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesAsyncClient", + "shortName": "KnowledgeBasesAsyncClient" + }, + "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesAsyncClient.create_knowledge_base", + "method": { + "fullName": "google.cloud.dialogflow.v2.KnowledgeBases.CreateKnowledgeBase", + "service": { + "fullName": "google.cloud.dialogflow.v2.KnowledgeBases", + "shortName": "KnowledgeBases" + }, + "shortName": "CreateKnowledgeBase" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflow_v2.types.CreateKnowledgeBaseRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "knowledge_base", + "type": "google.cloud.dialogflow_v2.types.KnowledgeBase" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflow_v2.types.KnowledgeBase", + "shortName": "create_knowledge_base" + }, + "description": "Sample for CreateKnowledgeBase", + "file": "dialogflow_v2_generated_knowledge_bases_create_knowledge_base_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v2_generated_KnowledgeBases_CreateKnowledgeBase_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": "dialogflow_v2_generated_knowledge_bases_create_knowledge_base_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesClient", + "shortName": "KnowledgeBasesClient" + }, + "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesClient.create_knowledge_base", + "method": { + "fullName": "google.cloud.dialogflow.v2.KnowledgeBases.CreateKnowledgeBase", + "service": { + "fullName": "google.cloud.dialogflow.v2.KnowledgeBases", + "shortName": "KnowledgeBases" + }, + "shortName": "CreateKnowledgeBase" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflow_v2.types.CreateKnowledgeBaseRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "knowledge_base", + "type": "google.cloud.dialogflow_v2.types.KnowledgeBase" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dialogflow_v2.types.KnowledgeBase", + "shortName": "create_knowledge_base" + }, + "description": "Sample for CreateKnowledgeBase", + "file": "dialogflow_v2_generated_knowledge_bases_create_knowledge_base_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v2_generated_KnowledgeBases_CreateKnowledgeBase_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": "dialogflow_v2_generated_knowledge_bases_create_knowledge_base_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesAsyncClient", + "shortName": "KnowledgeBasesAsyncClient" + }, + "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesAsyncClient.delete_knowledge_base", + "method": { + "fullName": "google.cloud.dialogflow.v2.KnowledgeBases.DeleteKnowledgeBase", + "service": { + "fullName": "google.cloud.dialogflow.v2.KnowledgeBases", + "shortName": "KnowledgeBases" + }, + "shortName": "DeleteKnowledgeBase" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflow_v2.types.DeleteKnowledgeBaseRequest" + }, + { + "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_knowledge_base" + }, + "description": "Sample for DeleteKnowledgeBase", + "file": "dialogflow_v2_generated_knowledge_bases_delete_knowledge_base_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v2_generated_KnowledgeBases_DeleteKnowledgeBase_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": "dialogflow_v2_generated_knowledge_bases_delete_knowledge_base_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesClient", + "shortName": "KnowledgeBasesClient" + }, + "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesClient.delete_knowledge_base", + "method": { + "fullName": "google.cloud.dialogflow.v2.KnowledgeBases.DeleteKnowledgeBase", + "service": { + "fullName": "google.cloud.dialogflow.v2.KnowledgeBases", + "shortName": "KnowledgeBases" + }, + "shortName": "DeleteKnowledgeBase" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflow_v2.types.DeleteKnowledgeBaseRequest" + }, + { + "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_knowledge_base" + }, + "description": "Sample for DeleteKnowledgeBase", + "file": "dialogflow_v2_generated_knowledge_bases_delete_knowledge_base_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v2_generated_KnowledgeBases_DeleteKnowledgeBase_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": "dialogflow_v2_generated_knowledge_bases_delete_knowledge_base_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesAsyncClient", + "shortName": "KnowledgeBasesAsyncClient" + }, + "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesAsyncClient.get_knowledge_base", + "method": { + "fullName": "google.cloud.dialogflow.v2.KnowledgeBases.GetKnowledgeBase", + "service": { + "fullName": "google.cloud.dialogflow.v2.KnowledgeBases", + "shortName": "KnowledgeBases" + }, + "shortName": "GetKnowledgeBase" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflow_v2.types.GetKnowledgeBaseRequest" + }, + { + "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.dialogflow_v2.types.KnowledgeBase", + "shortName": "get_knowledge_base" + }, + "description": "Sample for GetKnowledgeBase", + "file": "dialogflow_v2_generated_knowledge_bases_get_knowledge_base_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v2_generated_KnowledgeBases_GetKnowledgeBase_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": "dialogflow_v2_generated_knowledge_bases_get_knowledge_base_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesClient", + "shortName": "KnowledgeBasesClient" + }, + "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesClient.get_knowledge_base", + "method": { + "fullName": "google.cloud.dialogflow.v2.KnowledgeBases.GetKnowledgeBase", + "service": { + "fullName": "google.cloud.dialogflow.v2.KnowledgeBases", + "shortName": "KnowledgeBases" + }, + "shortName": "GetKnowledgeBase" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflow_v2.types.GetKnowledgeBaseRequest" + }, + { + "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.dialogflow_v2.types.KnowledgeBase", + "shortName": "get_knowledge_base" + }, + "description": "Sample for GetKnowledgeBase", + "file": "dialogflow_v2_generated_knowledge_bases_get_knowledge_base_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dialogflow_v2_generated_KnowledgeBases_GetKnowledgeBase_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": "dialogflow_v2_generated_knowledge_bases_get_knowledge_base_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesAsyncClient", + "shortName": "KnowledgeBasesAsyncClient" + }, + "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesAsyncClient.list_knowledge_bases", + "method": { + "fullName": "google.cloud.dialogflow.v2.KnowledgeBases.ListKnowledgeBases", + "service": { + "fullName": "google.cloud.dialogflow.v2.KnowledgeBases", + "shortName": "KnowledgeBases" + }, + "shortName": "ListKnowledgeBases" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dialogflow_v2.types.ListKnowledgeBasesRequest" + }, + { + "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.dialogflow_v2.services.knowledge_bases.pagers.ListKnowledgeBasesAsyncPager", + "shortName": "list_knowledge_bases" }, - "description": "Sample for BatchDeleteIntents", - "file": "dialogflow_v2_generated_intents_batch_delete_intents_async.py", + "description": "Sample for ListKnowledgeBases", + "file": "dialogflow_v2_generated_knowledge_bases_list_knowledge_bases_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Intents_BatchDeleteIntents_async", + "regionTag": "dialogflow_v2_generated_KnowledgeBases_ListKnowledgeBases_async", "segments": [ { - "end": 59, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 59, + "end": 52, "start": 27, "type": "SHORT" }, @@ -13367,52 +15687,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 56, - "start": 50, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 60, - "start": 57, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_intents_batch_delete_intents_async.py" + "title": "dialogflow_v2_generated_knowledge_bases_list_knowledge_bases_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflow_v2.IntentsClient", - "shortName": "IntentsClient" + "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesClient", + "shortName": "KnowledgeBasesClient" }, - "fullName": "google.cloud.dialogflow_v2.IntentsClient.batch_delete_intents", + "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesClient.list_knowledge_bases", "method": { - "fullName": "google.cloud.dialogflow.v2.Intents.BatchDeleteIntents", + "fullName": "google.cloud.dialogflow.v2.KnowledgeBases.ListKnowledgeBases", "service": { - "fullName": "google.cloud.dialogflow.v2.Intents", - "shortName": "Intents" + "fullName": "google.cloud.dialogflow.v2.KnowledgeBases", + "shortName": "KnowledgeBases" }, - "shortName": "BatchDeleteIntents" + "shortName": "ListKnowledgeBases" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.BatchDeleteIntentsRequest" + "type": "google.cloud.dialogflow_v2.types.ListKnowledgeBasesRequest" }, { "name": "parent", "type": "str" }, - { - "name": "intents", - "type": "MutableSequence[google.cloud.dialogflow_v2.types.Intent]" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -13426,22 +15742,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "batch_delete_intents" + "resultType": "google.cloud.dialogflow_v2.services.knowledge_bases.pagers.ListKnowledgeBasesPager", + "shortName": "list_knowledge_bases" }, - "description": "Sample for BatchDeleteIntents", - "file": "dialogflow_v2_generated_intents_batch_delete_intents_sync.py", + "description": "Sample for ListKnowledgeBases", + "file": "dialogflow_v2_generated_knowledge_bases_list_knowledge_bases_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Intents_BatchDeleteIntents_sync", + "regionTag": "dialogflow_v2_generated_KnowledgeBases_ListKnowledgeBases_sync", "segments": [ { - "end": 59, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 59, + "end": 52, "start": 27, "type": "SHORT" }, @@ -13451,56 +15767,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 56, - "start": 50, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 60, - "start": 57, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_intents_batch_delete_intents_sync.py" + "title": "dialogflow_v2_generated_knowledge_bases_list_knowledge_bases_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient", - "shortName": "IntentsAsyncClient" + "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesAsyncClient", + "shortName": "KnowledgeBasesAsyncClient" }, - "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient.batch_update_intents", + "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesAsyncClient.update_knowledge_base", "method": { - "fullName": "google.cloud.dialogflow.v2.Intents.BatchUpdateIntents", + "fullName": "google.cloud.dialogflow.v2.KnowledgeBases.UpdateKnowledgeBase", "service": { - "fullName": "google.cloud.dialogflow.v2.Intents", - "shortName": "Intents" + "fullName": "google.cloud.dialogflow.v2.KnowledgeBases", + "shortName": "KnowledgeBases" }, - "shortName": "BatchUpdateIntents" + "shortName": "UpdateKnowledgeBase" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.BatchUpdateIntentsRequest" - }, - { - "name": "parent", - "type": "str" + "type": "google.cloud.dialogflow_v2.types.UpdateKnowledgeBaseRequest" }, { - "name": "intent_batch_uri", - "type": "str" + "name": "knowledge_base", + "type": "google.cloud.dialogflow_v2.types.KnowledgeBase" }, { - "name": "intent_batch_inline", - "type": "google.cloud.dialogflow_v2.types.IntentBatch" + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -13515,22 +15827,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "batch_update_intents" + "resultType": "google.cloud.dialogflow_v2.types.KnowledgeBase", + "shortName": "update_knowledge_base" }, - "description": "Sample for BatchUpdateIntents", - "file": "dialogflow_v2_generated_intents_batch_update_intents_async.py", + "description": "Sample for UpdateKnowledgeBase", + "file": "dialogflow_v2_generated_knowledge_bases_update_knowledge_base_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Intents_BatchUpdateIntents_async", + "regionTag": "dialogflow_v2_generated_KnowledgeBases_UpdateKnowledgeBase_async", "segments": [ { - "end": 56, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 54, "start": 27, "type": "SHORT" }, @@ -13540,55 +15852,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_intents_batch_update_intents_async.py" + "title": "dialogflow_v2_generated_knowledge_bases_update_knowledge_base_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflow_v2.IntentsClient", - "shortName": "IntentsClient" + "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesClient", + "shortName": "KnowledgeBasesClient" }, - "fullName": "google.cloud.dialogflow_v2.IntentsClient.batch_update_intents", + "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesClient.update_knowledge_base", "method": { - "fullName": "google.cloud.dialogflow.v2.Intents.BatchUpdateIntents", + "fullName": "google.cloud.dialogflow.v2.KnowledgeBases.UpdateKnowledgeBase", "service": { - "fullName": "google.cloud.dialogflow.v2.Intents", - "shortName": "Intents" + "fullName": "google.cloud.dialogflow.v2.KnowledgeBases", + "shortName": "KnowledgeBases" }, - "shortName": "BatchUpdateIntents" + "shortName": "UpdateKnowledgeBase" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.BatchUpdateIntentsRequest" - }, - { - "name": "parent", - "type": "str" + "type": "google.cloud.dialogflow_v2.types.UpdateKnowledgeBaseRequest" }, { - "name": "intent_batch_uri", - "type": "str" + "name": "knowledge_base", + "type": "google.cloud.dialogflow_v2.types.KnowledgeBase" }, { - "name": "intent_batch_inline", - "type": "google.cloud.dialogflow_v2.types.IntentBatch" + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -13603,22 +15911,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "batch_update_intents" + "resultType": "google.cloud.dialogflow_v2.types.KnowledgeBase", + "shortName": "update_knowledge_base" }, - "description": "Sample for BatchUpdateIntents", - "file": "dialogflow_v2_generated_intents_batch_update_intents_sync.py", + "description": "Sample for UpdateKnowledgeBase", + "file": "dialogflow_v2_generated_knowledge_bases_update_knowledge_base_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Intents_BatchUpdateIntents_sync", + "regionTag": "dialogflow_v2_generated_KnowledgeBases_UpdateKnowledgeBase_sync", "segments": [ { - "end": 56, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 54, "start": 27, "type": "SHORT" }, @@ -13628,56 +15936,60 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_intents_batch_update_intents_sync.py" + "title": "dialogflow_v2_generated_knowledge_bases_update_knowledge_base_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient", - "shortName": "IntentsAsyncClient" + "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient", + "shortName": "ParticipantsAsyncClient" }, - "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient.create_intent", + "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient.analyze_content", "method": { - "fullName": "google.cloud.dialogflow.v2.Intents.CreateIntent", + "fullName": "google.cloud.dialogflow.v2.Participants.AnalyzeContent", "service": { - "fullName": "google.cloud.dialogflow.v2.Intents", - "shortName": "Intents" + "fullName": "google.cloud.dialogflow.v2.Participants", + "shortName": "Participants" }, - "shortName": "CreateIntent" + "shortName": "AnalyzeContent" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.CreateIntentRequest" + "type": "google.cloud.dialogflow_v2.types.AnalyzeContentRequest" }, { - "name": "parent", + "name": "participant", "type": "str" }, { - "name": "intent", - "type": "google.cloud.dialogflow_v2.types.Intent" + "name": "text_input", + "type": "google.cloud.dialogflow_v2.types.TextInput" + }, + { + "name": "event_input", + "type": "google.cloud.dialogflow_v2.types.EventInput" }, { - "name": "language_code", - "type": "str" + "name": "audio_input", + "type": "google.cloud.dialogflow_v2.types.AudioInput" }, { "name": "retry", @@ -13692,22 +16004,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.types.Intent", - "shortName": "create_intent" + "resultType": "google.cloud.dialogflow_v2.types.AnalyzeContentResponse", + "shortName": "analyze_content" }, - "description": "Sample for CreateIntent", - "file": "dialogflow_v2_generated_intents_create_intent_async.py", + "description": "Sample for AnalyzeContent", + "file": "dialogflow_v2_generated_participants_analyze_content_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Intents_CreateIntent_async", + "regionTag": "dialogflow_v2_generated_Participants_AnalyzeContent_async", "segments": [ { - "end": 55, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 56, "start": 27, "type": "SHORT" }, @@ -13717,55 +16029,59 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 53, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_intents_create_intent_async.py" + "title": "dialogflow_v2_generated_participants_analyze_content_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflow_v2.IntentsClient", - "shortName": "IntentsClient" + "fullName": "google.cloud.dialogflow_v2.ParticipantsClient", + "shortName": "ParticipantsClient" }, - "fullName": "google.cloud.dialogflow_v2.IntentsClient.create_intent", + "fullName": "google.cloud.dialogflow_v2.ParticipantsClient.analyze_content", "method": { - "fullName": "google.cloud.dialogflow.v2.Intents.CreateIntent", + "fullName": "google.cloud.dialogflow.v2.Participants.AnalyzeContent", "service": { - "fullName": "google.cloud.dialogflow.v2.Intents", - "shortName": "Intents" + "fullName": "google.cloud.dialogflow.v2.Participants", + "shortName": "Participants" }, - "shortName": "CreateIntent" + "shortName": "AnalyzeContent" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.CreateIntentRequest" + "type": "google.cloud.dialogflow_v2.types.AnalyzeContentRequest" }, { - "name": "parent", + "name": "participant", "type": "str" }, { - "name": "intent", - "type": "google.cloud.dialogflow_v2.types.Intent" + "name": "text_input", + "type": "google.cloud.dialogflow_v2.types.TextInput" }, { - "name": "language_code", - "type": "str" + "name": "event_input", + "type": "google.cloud.dialogflow_v2.types.EventInput" + }, + { + "name": "audio_input", + "type": "google.cloud.dialogflow_v2.types.AudioInput" }, { "name": "retry", @@ -13780,22 +16096,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.types.Intent", - "shortName": "create_intent" + "resultType": "google.cloud.dialogflow_v2.types.AnalyzeContentResponse", + "shortName": "analyze_content" }, - "description": "Sample for CreateIntent", - "file": "dialogflow_v2_generated_intents_create_intent_sync.py", + "description": "Sample for AnalyzeContent", + "file": "dialogflow_v2_generated_participants_analyze_content_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Intents_CreateIntent_sync", + "regionTag": "dialogflow_v2_generated_Participants_AnalyzeContent_sync", "segments": [ { - "end": 55, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 56, "start": 27, "type": "SHORT" }, @@ -13805,49 +16121,53 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 53, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_intents_create_intent_sync.py" + "title": "dialogflow_v2_generated_participants_analyze_content_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient", - "shortName": "IntentsAsyncClient" + "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient", + "shortName": "ParticipantsAsyncClient" }, - "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient.delete_intent", + "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient.create_participant", "method": { - "fullName": "google.cloud.dialogflow.v2.Intents.DeleteIntent", + "fullName": "google.cloud.dialogflow.v2.Participants.CreateParticipant", "service": { - "fullName": "google.cloud.dialogflow.v2.Intents", - "shortName": "Intents" + "fullName": "google.cloud.dialogflow.v2.Participants", + "shortName": "Participants" }, - "shortName": "DeleteIntent" + "shortName": "CreateParticipant" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.DeleteIntentRequest" + "type": "google.cloud.dialogflow_v2.types.CreateParticipantRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, + { + "name": "participant", + "type": "google.cloud.dialogflow_v2.types.Participant" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -13861,21 +16181,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_intent" + "resultType": "google.cloud.dialogflow_v2.types.Participant", + "shortName": "create_participant" }, - "description": "Sample for DeleteIntent", - "file": "dialogflow_v2_generated_intents_delete_intent_async.py", + "description": "Sample for CreateParticipant", + "file": "dialogflow_v2_generated_participants_create_participant_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Intents_DeleteIntent_async", + "regionTag": "dialogflow_v2_generated_Participants_CreateParticipant_async", "segments": [ { - "end": 49, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 51, "start": 27, "type": "SHORT" }, @@ -13890,41 +16211,47 @@ "type": "REQUEST_INITIALIZATION" }, { + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_intents_delete_intent_async.py" + "title": "dialogflow_v2_generated_participants_create_participant_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflow_v2.IntentsClient", - "shortName": "IntentsClient" + "fullName": "google.cloud.dialogflow_v2.ParticipantsClient", + "shortName": "ParticipantsClient" }, - "fullName": "google.cloud.dialogflow_v2.IntentsClient.delete_intent", + "fullName": "google.cloud.dialogflow_v2.ParticipantsClient.create_participant", "method": { - "fullName": "google.cloud.dialogflow.v2.Intents.DeleteIntent", + "fullName": "google.cloud.dialogflow.v2.Participants.CreateParticipant", "service": { - "fullName": "google.cloud.dialogflow.v2.Intents", - "shortName": "Intents" + "fullName": "google.cloud.dialogflow.v2.Participants", + "shortName": "Participants" }, - "shortName": "DeleteIntent" + "shortName": "CreateParticipant" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.DeleteIntentRequest" + "type": "google.cloud.dialogflow_v2.types.CreateParticipantRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, + { + "name": "participant", + "type": "google.cloud.dialogflow_v2.types.Participant" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -13938,21 +16265,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_intent" + "resultType": "google.cloud.dialogflow_v2.types.Participant", + "shortName": "create_participant" }, - "description": "Sample for DeleteIntent", - "file": "dialogflow_v2_generated_intents_delete_intent_sync.py", + "description": "Sample for CreateParticipant", + "file": "dialogflow_v2_generated_participants_create_participant_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Intents_DeleteIntent_sync", + "regionTag": "dialogflow_v2_generated_Participants_CreateParticipant_sync", "segments": [ { - "end": 49, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 51, "start": 27, "type": "SHORT" }, @@ -13967,46 +16295,44 @@ "type": "REQUEST_INITIALIZATION" }, { + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_intents_delete_intent_sync.py" + "title": "dialogflow_v2_generated_participants_create_participant_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient", - "shortName": "IntentsAsyncClient" + "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient", + "shortName": "ParticipantsAsyncClient" }, - "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient.get_intent", + "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient.get_participant", "method": { - "fullName": "google.cloud.dialogflow.v2.Intents.GetIntent", + "fullName": "google.cloud.dialogflow.v2.Participants.GetParticipant", "service": { - "fullName": "google.cloud.dialogflow.v2.Intents", - "shortName": "Intents" + "fullName": "google.cloud.dialogflow.v2.Participants", + "shortName": "Participants" }, - "shortName": "GetIntent" + "shortName": "GetParticipant" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetIntentRequest" + "type": "google.cloud.dialogflow_v2.types.GetParticipantRequest" }, { "name": "name", "type": "str" }, - { - "name": "language_code", - "type": "str" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -14020,14 +16346,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.types.Intent", - "shortName": "get_intent" + "resultType": "google.cloud.dialogflow_v2.types.Participant", + "shortName": "get_participant" }, - "description": "Sample for GetIntent", - "file": "dialogflow_v2_generated_intents_get_intent_async.py", + "description": "Sample for GetParticipant", + "file": "dialogflow_v2_generated_participants_get_participant_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Intents_GetIntent_async", + "regionTag": "dialogflow_v2_generated_Participants_GetParticipant_async", "segments": [ { "end": 51, @@ -14060,37 +16386,33 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_intents_get_intent_async.py" + "title": "dialogflow_v2_generated_participants_get_participant_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflow_v2.IntentsClient", - "shortName": "IntentsClient" + "fullName": "google.cloud.dialogflow_v2.ParticipantsClient", + "shortName": "ParticipantsClient" }, - "fullName": "google.cloud.dialogflow_v2.IntentsClient.get_intent", + "fullName": "google.cloud.dialogflow_v2.ParticipantsClient.get_participant", "method": { - "fullName": "google.cloud.dialogflow.v2.Intents.GetIntent", + "fullName": "google.cloud.dialogflow.v2.Participants.GetParticipant", "service": { - "fullName": "google.cloud.dialogflow.v2.Intents", - "shortName": "Intents" + "fullName": "google.cloud.dialogflow.v2.Participants", + "shortName": "Participants" }, - "shortName": "GetIntent" + "shortName": "GetParticipant" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetIntentRequest" + "type": "google.cloud.dialogflow_v2.types.GetParticipantRequest" }, { "name": "name", "type": "str" }, - { - "name": "language_code", - "type": "str" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -14104,14 +16426,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.types.Intent", - "shortName": "get_intent" + "resultType": "google.cloud.dialogflow_v2.types.Participant", + "shortName": "get_participant" }, - "description": "Sample for GetIntent", - "file": "dialogflow_v2_generated_intents_get_intent_sync.py", + "description": "Sample for GetParticipant", + "file": "dialogflow_v2_generated_participants_get_participant_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Intents_GetIntent_sync", + "regionTag": "dialogflow_v2_generated_Participants_GetParticipant_sync", "segments": [ { "end": 51, @@ -14144,38 +16466,34 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_intents_get_intent_sync.py" + "title": "dialogflow_v2_generated_participants_get_participant_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient", - "shortName": "IntentsAsyncClient" + "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient", + "shortName": "ParticipantsAsyncClient" }, - "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient.list_intents", + "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient.list_participants", "method": { - "fullName": "google.cloud.dialogflow.v2.Intents.ListIntents", + "fullName": "google.cloud.dialogflow.v2.Participants.ListParticipants", "service": { - "fullName": "google.cloud.dialogflow.v2.Intents", - "shortName": "Intents" + "fullName": "google.cloud.dialogflow.v2.Participants", + "shortName": "Participants" }, - "shortName": "ListIntents" + "shortName": "ListParticipants" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListIntentsRequest" + "type": "google.cloud.dialogflow_v2.types.ListParticipantsRequest" }, { "name": "parent", "type": "str" }, - { - "name": "language_code", - "type": "str" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -14189,14 +16507,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.services.intents.pagers.ListIntentsAsyncPager", - "shortName": "list_intents" + "resultType": "google.cloud.dialogflow_v2.services.participants.pagers.ListParticipantsAsyncPager", + "shortName": "list_participants" }, - "description": "Sample for ListIntents", - "file": "dialogflow_v2_generated_intents_list_intents_async.py", + "description": "Sample for ListParticipants", + "file": "dialogflow_v2_generated_participants_list_participants_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Intents_ListIntents_async", + "regionTag": "dialogflow_v2_generated_Participants_ListParticipants_async", "segments": [ { "end": 52, @@ -14229,37 +16547,33 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_intents_list_intents_async.py" + "title": "dialogflow_v2_generated_participants_list_participants_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflow_v2.IntentsClient", - "shortName": "IntentsClient" + "fullName": "google.cloud.dialogflow_v2.ParticipantsClient", + "shortName": "ParticipantsClient" }, - "fullName": "google.cloud.dialogflow_v2.IntentsClient.list_intents", + "fullName": "google.cloud.dialogflow_v2.ParticipantsClient.list_participants", "method": { - "fullName": "google.cloud.dialogflow.v2.Intents.ListIntents", + "fullName": "google.cloud.dialogflow.v2.Participants.ListParticipants", "service": { - "fullName": "google.cloud.dialogflow.v2.Intents", - "shortName": "Intents" + "fullName": "google.cloud.dialogflow.v2.Participants", + "shortName": "Participants" }, - "shortName": "ListIntents" + "shortName": "ListParticipants" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListIntentsRequest" + "type": "google.cloud.dialogflow_v2.types.ListParticipantsRequest" }, { "name": "parent", "type": "str" }, - { - "name": "language_code", - "type": "str" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -14273,14 +16587,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.services.intents.pagers.ListIntentsPager", - "shortName": "list_intents" + "resultType": "google.cloud.dialogflow_v2.services.participants.pagers.ListParticipantsPager", + "shortName": "list_participants" }, - "description": "Sample for ListIntents", - "file": "dialogflow_v2_generated_intents_list_intents_sync.py", + "description": "Sample for ListParticipants", + "file": "dialogflow_v2_generated_participants_list_participants_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Intents_ListIntents_sync", + "regionTag": "dialogflow_v2_generated_Participants_ListParticipants_sync", "segments": [ { "end": 52, @@ -14313,41 +16627,29 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_intents_list_intents_sync.py" + "title": "dialogflow_v2_generated_participants_list_participants_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient", - "shortName": "IntentsAsyncClient" + "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient", + "shortName": "ParticipantsAsyncClient" }, - "fullName": "google.cloud.dialogflow_v2.IntentsAsyncClient.update_intent", + "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient.streaming_analyze_content", "method": { - "fullName": "google.cloud.dialogflow.v2.Intents.UpdateIntent", + "fullName": "google.cloud.dialogflow.v2.Participants.StreamingAnalyzeContent", "service": { - "fullName": "google.cloud.dialogflow.v2.Intents", - "shortName": "Intents" + "fullName": "google.cloud.dialogflow.v2.Participants", + "shortName": "Participants" }, - "shortName": "UpdateIntent" + "shortName": "StreamingAnalyzeContent" }, "parameters": [ { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.UpdateIntentRequest" - }, - { - "name": "intent", - "type": "google.cloud.dialogflow_v2.types.Intent" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "requests", + "type": "Iterator[google.cloud.dialogflow_v2.types.StreamingAnalyzeContentRequest]" }, { "name": "retry", @@ -14362,22 +16664,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.types.Intent", - "shortName": "update_intent" + "resultType": "Iterable[google.cloud.dialogflow_v2.types.StreamingAnalyzeContentResponse]", + "shortName": "streaming_analyze_content" }, - "description": "Sample for UpdateIntent", - "file": "dialogflow_v2_generated_intents_update_intent_async.py", + "description": "Sample for StreamingAnalyzeContent", + "file": "dialogflow_v2_generated_participants_streaming_analyze_content_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Intents_UpdateIntent_async", + "regionTag": "dialogflow_v2_generated_Participants_StreamingAnalyzeContent_async", "segments": [ { - "end": 54, + "end": 69, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 69, "start": 27, "type": "SHORT" }, @@ -14387,55 +16689,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 62, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 49, + "end": 65, + "start": 63, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 70, + "start": 66, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_intents_update_intent_async.py" + "title": "dialogflow_v2_generated_participants_streaming_analyze_content_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflow_v2.IntentsClient", - "shortName": "IntentsClient" + "fullName": "google.cloud.dialogflow_v2.ParticipantsClient", + "shortName": "ParticipantsClient" }, - "fullName": "google.cloud.dialogflow_v2.IntentsClient.update_intent", + "fullName": "google.cloud.dialogflow_v2.ParticipantsClient.streaming_analyze_content", "method": { - "fullName": "google.cloud.dialogflow.v2.Intents.UpdateIntent", + "fullName": "google.cloud.dialogflow.v2.Participants.StreamingAnalyzeContent", "service": { - "fullName": "google.cloud.dialogflow.v2.Intents", - "shortName": "Intents" + "fullName": "google.cloud.dialogflow.v2.Participants", + "shortName": "Participants" }, - "shortName": "UpdateIntent" + "shortName": "StreamingAnalyzeContent" }, "parameters": [ { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.UpdateIntentRequest" - }, - { - "name": "intent", - "type": "google.cloud.dialogflow_v2.types.Intent" - }, - { - "name": "language_code", - "type": "str" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "requests", + "type": "Iterator[google.cloud.dialogflow_v2.types.StreamingAnalyzeContentRequest]" }, { "name": "retry", @@ -14450,22 +16740,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.types.Intent", - "shortName": "update_intent" + "resultType": "Iterable[google.cloud.dialogflow_v2.types.StreamingAnalyzeContentResponse]", + "shortName": "streaming_analyze_content" }, - "description": "Sample for UpdateIntent", - "file": "dialogflow_v2_generated_intents_update_intent_sync.py", + "description": "Sample for StreamingAnalyzeContent", + "file": "dialogflow_v2_generated_participants_streaming_analyze_content_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Intents_UpdateIntent_sync", + "regionTag": "dialogflow_v2_generated_Participants_StreamingAnalyzeContent_sync", "segments": [ { - "end": 54, + "end": 69, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 69, "start": 27, "type": "SHORT" }, @@ -14475,53 +16765,49 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 62, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 49, + "end": 65, + "start": 63, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 70, + "start": 66, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_intents_update_intent_sync.py" + "title": "dialogflow_v2_generated_participants_streaming_analyze_content_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesAsyncClient", - "shortName": "KnowledgeBasesAsyncClient" + "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient", + "shortName": "ParticipantsAsyncClient" }, - "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesAsyncClient.create_knowledge_base", + "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient.suggest_articles", "method": { - "fullName": "google.cloud.dialogflow.v2.KnowledgeBases.CreateKnowledgeBase", + "fullName": "google.cloud.dialogflow.v2.Participants.SuggestArticles", "service": { - "fullName": "google.cloud.dialogflow.v2.KnowledgeBases", - "shortName": "KnowledgeBases" + "fullName": "google.cloud.dialogflow.v2.Participants", + "shortName": "Participants" }, - "shortName": "CreateKnowledgeBase" + "shortName": "SuggestArticles" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.CreateKnowledgeBaseRequest" + "type": "google.cloud.dialogflow_v2.types.SuggestArticlesRequest" }, { "name": "parent", "type": "str" }, - { - "name": "knowledge_base", - "type": "google.cloud.dialogflow_v2.types.KnowledgeBase" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -14535,22 +16821,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.types.KnowledgeBase", - "shortName": "create_knowledge_base" + "resultType": "google.cloud.dialogflow_v2.types.SuggestArticlesResponse", + "shortName": "suggest_articles" }, - "description": "Sample for CreateKnowledgeBase", - "file": "dialogflow_v2_generated_knowledge_bases_create_knowledge_base_async.py", + "description": "Sample for SuggestArticles", + "file": "dialogflow_v2_generated_participants_suggest_articles_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_KnowledgeBases_CreateKnowledgeBase_async", + "regionTag": "dialogflow_v2_generated_Participants_SuggestArticles_async", "segments": [ { - "end": 55, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 51, "start": 27, "type": "SHORT" }, @@ -14560,52 +16846,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_knowledge_bases_create_knowledge_base_async.py" + "title": "dialogflow_v2_generated_participants_suggest_articles_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesClient", - "shortName": "KnowledgeBasesClient" + "fullName": "google.cloud.dialogflow_v2.ParticipantsClient", + "shortName": "ParticipantsClient" }, - "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesClient.create_knowledge_base", + "fullName": "google.cloud.dialogflow_v2.ParticipantsClient.suggest_articles", "method": { - "fullName": "google.cloud.dialogflow.v2.KnowledgeBases.CreateKnowledgeBase", + "fullName": "google.cloud.dialogflow.v2.Participants.SuggestArticles", "service": { - "fullName": "google.cloud.dialogflow.v2.KnowledgeBases", - "shortName": "KnowledgeBases" + "fullName": "google.cloud.dialogflow.v2.Participants", + "shortName": "Participants" }, - "shortName": "CreateKnowledgeBase" + "shortName": "SuggestArticles" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.CreateKnowledgeBaseRequest" + "type": "google.cloud.dialogflow_v2.types.SuggestArticlesRequest" }, { "name": "parent", "type": "str" }, - { - "name": "knowledge_base", - "type": "google.cloud.dialogflow_v2.types.KnowledgeBase" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -14619,22 +16901,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.types.KnowledgeBase", - "shortName": "create_knowledge_base" + "resultType": "google.cloud.dialogflow_v2.types.SuggestArticlesResponse", + "shortName": "suggest_articles" }, - "description": "Sample for CreateKnowledgeBase", - "file": "dialogflow_v2_generated_knowledge_bases_create_knowledge_base_sync.py", + "description": "Sample for SuggestArticles", + "file": "dialogflow_v2_generated_participants_suggest_articles_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_KnowledgeBases_CreateKnowledgeBase_sync", + "regionTag": "dialogflow_v2_generated_Participants_SuggestArticles_sync", "segments": [ { - "end": 55, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 51, "start": 27, "type": "SHORT" }, @@ -14644,47 +16926,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_knowledge_bases_create_knowledge_base_sync.py" + "title": "dialogflow_v2_generated_participants_suggest_articles_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesAsyncClient", - "shortName": "KnowledgeBasesAsyncClient" + "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient", + "shortName": "ParticipantsAsyncClient" }, - "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesAsyncClient.delete_knowledge_base", + "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient.suggest_faq_answers", "method": { - "fullName": "google.cloud.dialogflow.v2.KnowledgeBases.DeleteKnowledgeBase", + "fullName": "google.cloud.dialogflow.v2.Participants.SuggestFaqAnswers", "service": { - "fullName": "google.cloud.dialogflow.v2.KnowledgeBases", - "shortName": "KnowledgeBases" + "fullName": "google.cloud.dialogflow.v2.Participants", + "shortName": "Participants" }, - "shortName": "DeleteKnowledgeBase" + "shortName": "SuggestFaqAnswers" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.DeleteKnowledgeBaseRequest" + "type": "google.cloud.dialogflow_v2.types.SuggestFaqAnswersRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -14700,21 +16982,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_knowledge_base" + "resultType": "google.cloud.dialogflow_v2.types.SuggestFaqAnswersResponse", + "shortName": "suggest_faq_answers" }, - "description": "Sample for DeleteKnowledgeBase", - "file": "dialogflow_v2_generated_knowledge_bases_delete_knowledge_base_async.py", + "description": "Sample for SuggestFaqAnswers", + "file": "dialogflow_v2_generated_participants_suggest_faq_answers_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_KnowledgeBases_DeleteKnowledgeBase_async", + "regionTag": "dialogflow_v2_generated_Participants_SuggestFaqAnswers_async", "segments": [ { - "end": 49, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 51, "start": 27, "type": "SHORT" }, @@ -14729,39 +17012,41 @@ "type": "REQUEST_INITIALIZATION" }, { + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_knowledge_bases_delete_knowledge_base_async.py" + "title": "dialogflow_v2_generated_participants_suggest_faq_answers_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesClient", - "shortName": "KnowledgeBasesClient" + "fullName": "google.cloud.dialogflow_v2.ParticipantsClient", + "shortName": "ParticipantsClient" }, - "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesClient.delete_knowledge_base", + "fullName": "google.cloud.dialogflow_v2.ParticipantsClient.suggest_faq_answers", "method": { - "fullName": "google.cloud.dialogflow.v2.KnowledgeBases.DeleteKnowledgeBase", + "fullName": "google.cloud.dialogflow.v2.Participants.SuggestFaqAnswers", "service": { - "fullName": "google.cloud.dialogflow.v2.KnowledgeBases", - "shortName": "KnowledgeBases" + "fullName": "google.cloud.dialogflow.v2.Participants", + "shortName": "Participants" }, - "shortName": "DeleteKnowledgeBase" + "shortName": "SuggestFaqAnswers" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.DeleteKnowledgeBaseRequest" + "type": "google.cloud.dialogflow_v2.types.SuggestFaqAnswersRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -14777,21 +17062,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_knowledge_base" + "resultType": "google.cloud.dialogflow_v2.types.SuggestFaqAnswersResponse", + "shortName": "suggest_faq_answers" }, - "description": "Sample for DeleteKnowledgeBase", - "file": "dialogflow_v2_generated_knowledge_bases_delete_knowledge_base_sync.py", + "description": "Sample for SuggestFaqAnswers", + "file": "dialogflow_v2_generated_participants_suggest_faq_answers_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_KnowledgeBases_DeleteKnowledgeBase_sync", + "regionTag": "dialogflow_v2_generated_Participants_SuggestFaqAnswers_sync", "segments": [ { - "end": 49, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 51, "start": 27, "type": "SHORT" }, @@ -14806,41 +17092,39 @@ "type": "REQUEST_INITIALIZATION" }, { + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_knowledge_bases_delete_knowledge_base_sync.py" + "title": "dialogflow_v2_generated_participants_suggest_faq_answers_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesAsyncClient", - "shortName": "KnowledgeBasesAsyncClient" + "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient", + "shortName": "ParticipantsAsyncClient" }, - "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesAsyncClient.get_knowledge_base", + "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient.suggest_knowledge_assist", "method": { - "fullName": "google.cloud.dialogflow.v2.KnowledgeBases.GetKnowledgeBase", + "fullName": "google.cloud.dialogflow.v2.Participants.SuggestKnowledgeAssist", "service": { - "fullName": "google.cloud.dialogflow.v2.KnowledgeBases", - "shortName": "KnowledgeBases" + "fullName": "google.cloud.dialogflow.v2.Participants", + "shortName": "Participants" }, - "shortName": "GetKnowledgeBase" + "shortName": "SuggestKnowledgeAssist" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetKnowledgeBaseRequest" - }, - { - "name": "name", - "type": "str" + "type": "google.cloud.dialogflow_v2.types.SuggestKnowledgeAssistRequest" }, { "name": "retry", @@ -14855,14 +17139,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.types.KnowledgeBase", - "shortName": "get_knowledge_base" + "resultType": "google.cloud.dialogflow_v2.types.SuggestKnowledgeAssistResponse", + "shortName": "suggest_knowledge_assist" }, - "description": "Sample for GetKnowledgeBase", - "file": "dialogflow_v2_generated_knowledge_bases_get_knowledge_base_async.py", + "description": "Sample for SuggestKnowledgeAssist", + "file": "dialogflow_v2_generated_participants_suggest_knowledge_assist_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_KnowledgeBases_GetKnowledgeBase_async", + "regionTag": "dialogflow_v2_generated_Participants_SuggestKnowledgeAssist_async", "segments": [ { "end": 51, @@ -14895,32 +17179,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_knowledge_bases_get_knowledge_base_async.py" + "title": "dialogflow_v2_generated_participants_suggest_knowledge_assist_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesClient", - "shortName": "KnowledgeBasesClient" + "fullName": "google.cloud.dialogflow_v2.ParticipantsClient", + "shortName": "ParticipantsClient" }, - "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesClient.get_knowledge_base", + "fullName": "google.cloud.dialogflow_v2.ParticipantsClient.suggest_knowledge_assist", "method": { - "fullName": "google.cloud.dialogflow.v2.KnowledgeBases.GetKnowledgeBase", + "fullName": "google.cloud.dialogflow.v2.Participants.SuggestKnowledgeAssist", "service": { - "fullName": "google.cloud.dialogflow.v2.KnowledgeBases", - "shortName": "KnowledgeBases" + "fullName": "google.cloud.dialogflow.v2.Participants", + "shortName": "Participants" }, - "shortName": "GetKnowledgeBase" + "shortName": "SuggestKnowledgeAssist" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetKnowledgeBaseRequest" - }, - { - "name": "name", - "type": "str" + "type": "google.cloud.dialogflow_v2.types.SuggestKnowledgeAssistRequest" }, { "name": "retry", @@ -14935,14 +17215,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.types.KnowledgeBase", - "shortName": "get_knowledge_base" + "resultType": "google.cloud.dialogflow_v2.types.SuggestKnowledgeAssistResponse", + "shortName": "suggest_knowledge_assist" }, - "description": "Sample for GetKnowledgeBase", - "file": "dialogflow_v2_generated_knowledge_bases_get_knowledge_base_sync.py", + "description": "Sample for SuggestKnowledgeAssist", + "file": "dialogflow_v2_generated_participants_suggest_knowledge_assist_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_KnowledgeBases_GetKnowledgeBase_sync", + "regionTag": "dialogflow_v2_generated_Participants_SuggestKnowledgeAssist_sync", "segments": [ { "end": 51, @@ -14975,29 +17255,29 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_knowledge_bases_get_knowledge_base_sync.py" + "title": "dialogflow_v2_generated_participants_suggest_knowledge_assist_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesAsyncClient", - "shortName": "KnowledgeBasesAsyncClient" + "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient", + "shortName": "ParticipantsAsyncClient" }, - "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesAsyncClient.list_knowledge_bases", + "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient.suggest_smart_replies", "method": { - "fullName": "google.cloud.dialogflow.v2.KnowledgeBases.ListKnowledgeBases", + "fullName": "google.cloud.dialogflow.v2.Participants.SuggestSmartReplies", "service": { - "fullName": "google.cloud.dialogflow.v2.KnowledgeBases", - "shortName": "KnowledgeBases" + "fullName": "google.cloud.dialogflow.v2.Participants", + "shortName": "Participants" }, - "shortName": "ListKnowledgeBases" + "shortName": "SuggestSmartReplies" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListKnowledgeBasesRequest" + "type": "google.cloud.dialogflow_v2.types.SuggestSmartRepliesRequest" }, { "name": "parent", @@ -15016,22 +17296,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.services.knowledge_bases.pagers.ListKnowledgeBasesAsyncPager", - "shortName": "list_knowledge_bases" + "resultType": "google.cloud.dialogflow_v2.types.SuggestSmartRepliesResponse", + "shortName": "suggest_smart_replies" }, - "description": "Sample for ListKnowledgeBases", - "file": "dialogflow_v2_generated_knowledge_bases_list_knowledge_bases_async.py", + "description": "Sample for SuggestSmartReplies", + "file": "dialogflow_v2_generated_participants_suggest_smart_replies_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_KnowledgeBases_ListKnowledgeBases_async", + "regionTag": "dialogflow_v2_generated_Participants_SuggestSmartReplies_async", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -15051,33 +17331,33 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_knowledge_bases_list_knowledge_bases_async.py" + "title": "dialogflow_v2_generated_participants_suggest_smart_replies_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesClient", - "shortName": "KnowledgeBasesClient" + "fullName": "google.cloud.dialogflow_v2.ParticipantsClient", + "shortName": "ParticipantsClient" }, - "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesClient.list_knowledge_bases", + "fullName": "google.cloud.dialogflow_v2.ParticipantsClient.suggest_smart_replies", "method": { - "fullName": "google.cloud.dialogflow.v2.KnowledgeBases.ListKnowledgeBases", + "fullName": "google.cloud.dialogflow.v2.Participants.SuggestSmartReplies", "service": { - "fullName": "google.cloud.dialogflow.v2.KnowledgeBases", - "shortName": "KnowledgeBases" + "fullName": "google.cloud.dialogflow.v2.Participants", + "shortName": "Participants" }, - "shortName": "ListKnowledgeBases" + "shortName": "SuggestSmartReplies" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListKnowledgeBasesRequest" + "type": "google.cloud.dialogflow_v2.types.SuggestSmartRepliesRequest" }, { "name": "parent", @@ -15096,22 +17376,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.services.knowledge_bases.pagers.ListKnowledgeBasesPager", - "shortName": "list_knowledge_bases" + "resultType": "google.cloud.dialogflow_v2.types.SuggestSmartRepliesResponse", + "shortName": "suggest_smart_replies" }, - "description": "Sample for ListKnowledgeBases", - "file": "dialogflow_v2_generated_knowledge_bases_list_knowledge_bases_sync.py", + "description": "Sample for SuggestSmartReplies", + "file": "dialogflow_v2_generated_participants_suggest_smart_replies_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_KnowledgeBases_ListKnowledgeBases_sync", + "regionTag": "dialogflow_v2_generated_Participants_SuggestSmartReplies_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -15131,38 +17411,38 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_knowledge_bases_list_knowledge_bases_sync.py" + "title": "dialogflow_v2_generated_participants_suggest_smart_replies_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesAsyncClient", - "shortName": "KnowledgeBasesAsyncClient" + "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient", + "shortName": "ParticipantsAsyncClient" }, - "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesAsyncClient.update_knowledge_base", + "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient.update_participant", "method": { - "fullName": "google.cloud.dialogflow.v2.KnowledgeBases.UpdateKnowledgeBase", + "fullName": "google.cloud.dialogflow.v2.Participants.UpdateParticipant", "service": { - "fullName": "google.cloud.dialogflow.v2.KnowledgeBases", - "shortName": "KnowledgeBases" + "fullName": "google.cloud.dialogflow.v2.Participants", + "shortName": "Participants" }, - "shortName": "UpdateKnowledgeBase" + "shortName": "UpdateParticipant" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.UpdateKnowledgeBaseRequest" + "type": "google.cloud.dialogflow_v2.types.UpdateParticipantRequest" }, { - "name": "knowledge_base", - "type": "google.cloud.dialogflow_v2.types.KnowledgeBase" + "name": "participant", + "type": "google.cloud.dialogflow_v2.types.Participant" }, { "name": "update_mask", @@ -15181,22 +17461,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.types.KnowledgeBase", - "shortName": "update_knowledge_base" + "resultType": "google.cloud.dialogflow_v2.types.Participant", + "shortName": "update_participant" }, - "description": "Sample for UpdateKnowledgeBase", - "file": "dialogflow_v2_generated_knowledge_bases_update_knowledge_base_async.py", + "description": "Sample for UpdateParticipant", + "file": "dialogflow_v2_generated_participants_update_participant_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_KnowledgeBases_UpdateKnowledgeBase_async", + "regionTag": "dialogflow_v2_generated_Participants_UpdateParticipant_async", "segments": [ { - "end": 54, + "end": 50, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 50, "start": 27, "type": "SHORT" }, @@ -15206,47 +17486,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 44, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 49, + "end": 47, + "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 51, + "start": 48, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_knowledge_bases_update_knowledge_base_async.py" + "title": "dialogflow_v2_generated_participants_update_participant_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesClient", - "shortName": "KnowledgeBasesClient" + "fullName": "google.cloud.dialogflow_v2.ParticipantsClient", + "shortName": "ParticipantsClient" }, - "fullName": "google.cloud.dialogflow_v2.KnowledgeBasesClient.update_knowledge_base", + "fullName": "google.cloud.dialogflow_v2.ParticipantsClient.update_participant", "method": { - "fullName": "google.cloud.dialogflow.v2.KnowledgeBases.UpdateKnowledgeBase", + "fullName": "google.cloud.dialogflow.v2.Participants.UpdateParticipant", "service": { - "fullName": "google.cloud.dialogflow.v2.KnowledgeBases", - "shortName": "KnowledgeBases" + "fullName": "google.cloud.dialogflow.v2.Participants", + "shortName": "Participants" }, - "shortName": "UpdateKnowledgeBase" + "shortName": "UpdateParticipant" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.UpdateKnowledgeBaseRequest" + "type": "google.cloud.dialogflow_v2.types.UpdateParticipantRequest" }, { - "name": "knowledge_base", - "type": "google.cloud.dialogflow_v2.types.KnowledgeBase" + "name": "participant", + "type": "google.cloud.dialogflow_v2.types.Participant" }, { "name": "update_mask", @@ -15265,22 +17545,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.types.KnowledgeBase", - "shortName": "update_knowledge_base" + "resultType": "google.cloud.dialogflow_v2.types.Participant", + "shortName": "update_participant" }, - "description": "Sample for UpdateKnowledgeBase", - "file": "dialogflow_v2_generated_knowledge_bases_update_knowledge_base_sync.py", + "description": "Sample for UpdateParticipant", + "file": "dialogflow_v2_generated_participants_update_participant_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_KnowledgeBases_UpdateKnowledgeBase_sync", + "regionTag": "dialogflow_v2_generated_Participants_UpdateParticipant_sync", "segments": [ { - "end": 54, + "end": 50, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 50, "start": 27, "type": "SHORT" }, @@ -15290,60 +17570,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 44, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 49, + "end": 47, + "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 51, + "start": 48, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_knowledge_bases_update_knowledge_base_sync.py" + "title": "dialogflow_v2_generated_participants_update_participant_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient", - "shortName": "ParticipantsAsyncClient" + "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesAsyncClient", + "shortName": "SessionEntityTypesAsyncClient" }, - "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient.analyze_content", + "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesAsyncClient.create_session_entity_type", "method": { - "fullName": "google.cloud.dialogflow.v2.Participants.AnalyzeContent", + "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes.CreateSessionEntityType", "service": { - "fullName": "google.cloud.dialogflow.v2.Participants", - "shortName": "Participants" + "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes", + "shortName": "SessionEntityTypes" }, - "shortName": "AnalyzeContent" + "shortName": "CreateSessionEntityType" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.AnalyzeContentRequest" + "type": "google.cloud.dialogflow_v2.types.CreateSessionEntityTypeRequest" }, { - "name": "participant", + "name": "parent", "type": "str" }, { - "name": "text_input", - "type": "google.cloud.dialogflow_v2.types.TextInput" - }, - { - "name": "event_input", - "type": "google.cloud.dialogflow_v2.types.EventInput" - }, - { - "name": "audio_input", - "type": "google.cloud.dialogflow_v2.types.AudioInput" + "name": "session_entity_type", + "type": "google.cloud.dialogflow_v2.types.SessionEntityType" }, { "name": "retry", @@ -15358,22 +17630,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.types.AnalyzeContentResponse", - "shortName": "analyze_content" + "resultType": "google.cloud.dialogflow_v2.types.SessionEntityType", + "shortName": "create_session_entity_type" }, - "description": "Sample for AnalyzeContent", - "file": "dialogflow_v2_generated_participants_analyze_content_async.py", + "description": "Sample for CreateSessionEntityType", + "file": "dialogflow_v2_generated_session_entity_types_create_session_entity_type_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Participants_AnalyzeContent_async", + "regionTag": "dialogflow_v2_generated_SessionEntityTypes_CreateSessionEntityType_async", "segments": [ { - "end": 56, + "end": 58, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 58, "start": 27, "type": "SHORT" }, @@ -15383,59 +17655,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 52, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 51, + "end": 55, + "start": 53, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 59, + "start": 56, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_participants_analyze_content_async.py" + "title": "dialogflow_v2_generated_session_entity_types_create_session_entity_type_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflow_v2.ParticipantsClient", - "shortName": "ParticipantsClient" + "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesClient", + "shortName": "SessionEntityTypesClient" }, - "fullName": "google.cloud.dialogflow_v2.ParticipantsClient.analyze_content", + "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesClient.create_session_entity_type", "method": { - "fullName": "google.cloud.dialogflow.v2.Participants.AnalyzeContent", + "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes.CreateSessionEntityType", "service": { - "fullName": "google.cloud.dialogflow.v2.Participants", - "shortName": "Participants" + "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes", + "shortName": "SessionEntityTypes" }, - "shortName": "AnalyzeContent" + "shortName": "CreateSessionEntityType" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.AnalyzeContentRequest" + "type": "google.cloud.dialogflow_v2.types.CreateSessionEntityTypeRequest" }, { - "name": "participant", + "name": "parent", "type": "str" }, { - "name": "text_input", - "type": "google.cloud.dialogflow_v2.types.TextInput" - }, - { - "name": "event_input", - "type": "google.cloud.dialogflow_v2.types.EventInput" - }, - { - "name": "audio_input", - "type": "google.cloud.dialogflow_v2.types.AudioInput" + "name": "session_entity_type", + "type": "google.cloud.dialogflow_v2.types.SessionEntityType" }, { "name": "retry", @@ -15450,22 +17714,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.types.AnalyzeContentResponse", - "shortName": "analyze_content" + "resultType": "google.cloud.dialogflow_v2.types.SessionEntityType", + "shortName": "create_session_entity_type" }, - "description": "Sample for AnalyzeContent", - "file": "dialogflow_v2_generated_participants_analyze_content_sync.py", + "description": "Sample for CreateSessionEntityType", + "file": "dialogflow_v2_generated_session_entity_types_create_session_entity_type_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Participants_AnalyzeContent_sync", + "regionTag": "dialogflow_v2_generated_SessionEntityTypes_CreateSessionEntityType_sync", "segments": [ { - "end": 56, + "end": 58, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 58, "start": 27, "type": "SHORT" }, @@ -15475,53 +17739,49 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 52, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 51, + "end": 55, + "start": 53, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 59, + "start": 56, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_participants_analyze_content_sync.py" + "title": "dialogflow_v2_generated_session_entity_types_create_session_entity_type_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient", - "shortName": "ParticipantsAsyncClient" + "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesAsyncClient", + "shortName": "SessionEntityTypesAsyncClient" }, - "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient.create_participant", + "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesAsyncClient.delete_session_entity_type", "method": { - "fullName": "google.cloud.dialogflow.v2.Participants.CreateParticipant", + "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes.DeleteSessionEntityType", "service": { - "fullName": "google.cloud.dialogflow.v2.Participants", - "shortName": "Participants" + "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes", + "shortName": "SessionEntityTypes" }, - "shortName": "CreateParticipant" + "shortName": "DeleteSessionEntityType" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.CreateParticipantRequest" + "type": "google.cloud.dialogflow_v2.types.DeleteSessionEntityTypeRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, - { - "name": "participant", - "type": "google.cloud.dialogflow_v2.types.Participant" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -15535,22 +17795,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.types.Participant", - "shortName": "create_participant" + "shortName": "delete_session_entity_type" }, - "description": "Sample for CreateParticipant", - "file": "dialogflow_v2_generated_participants_create_participant_async.py", + "description": "Sample for DeleteSessionEntityType", + "file": "dialogflow_v2_generated_session_entity_types_delete_session_entity_type_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Participants_CreateParticipant_async", + "regionTag": "dialogflow_v2_generated_SessionEntityTypes_DeleteSessionEntityType_async", "segments": [ { - "end": 51, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 49, "start": 27, "type": "SHORT" }, @@ -15565,47 +17824,41 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_participants_create_participant_async.py" + "title": "dialogflow_v2_generated_session_entity_types_delete_session_entity_type_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflow_v2.ParticipantsClient", - "shortName": "ParticipantsClient" + "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesClient", + "shortName": "SessionEntityTypesClient" }, - "fullName": "google.cloud.dialogflow_v2.ParticipantsClient.create_participant", + "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesClient.delete_session_entity_type", "method": { - "fullName": "google.cloud.dialogflow.v2.Participants.CreateParticipant", + "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes.DeleteSessionEntityType", "service": { - "fullName": "google.cloud.dialogflow.v2.Participants", - "shortName": "Participants" + "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes", + "shortName": "SessionEntityTypes" }, - "shortName": "CreateParticipant" + "shortName": "DeleteSessionEntityType" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.CreateParticipantRequest" + "type": "google.cloud.dialogflow_v2.types.DeleteSessionEntityTypeRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, - { - "name": "participant", - "type": "google.cloud.dialogflow_v2.types.Participant" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -15619,22 +17872,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.types.Participant", - "shortName": "create_participant" + "shortName": "delete_session_entity_type" }, - "description": "Sample for CreateParticipant", - "file": "dialogflow_v2_generated_participants_create_participant_sync.py", + "description": "Sample for DeleteSessionEntityType", + "file": "dialogflow_v2_generated_session_entity_types_delete_session_entity_type_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Participants_CreateParticipant_sync", + "regionTag": "dialogflow_v2_generated_SessionEntityTypes_DeleteSessionEntityType_sync", "segments": [ { - "end": 51, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 49, "start": 27, "type": "SHORT" }, @@ -15649,39 +17901,37 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_participants_create_participant_sync.py" + "title": "dialogflow_v2_generated_session_entity_types_delete_session_entity_type_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient", - "shortName": "ParticipantsAsyncClient" + "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesAsyncClient", + "shortName": "SessionEntityTypesAsyncClient" }, - "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient.get_participant", + "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesAsyncClient.get_session_entity_type", "method": { - "fullName": "google.cloud.dialogflow.v2.Participants.GetParticipant", + "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes.GetSessionEntityType", "service": { - "fullName": "google.cloud.dialogflow.v2.Participants", - "shortName": "Participants" + "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes", + "shortName": "SessionEntityTypes" }, - "shortName": "GetParticipant" + "shortName": "GetSessionEntityType" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetParticipantRequest" + "type": "google.cloud.dialogflow_v2.types.GetSessionEntityTypeRequest" }, { "name": "name", @@ -15700,14 +17950,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.types.Participant", - "shortName": "get_participant" + "resultType": "google.cloud.dialogflow_v2.types.SessionEntityType", + "shortName": "get_session_entity_type" }, - "description": "Sample for GetParticipant", - "file": "dialogflow_v2_generated_participants_get_participant_async.py", + "description": "Sample for GetSessionEntityType", + "file": "dialogflow_v2_generated_session_entity_types_get_session_entity_type_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Participants_GetParticipant_async", + "regionTag": "dialogflow_v2_generated_SessionEntityTypes_GetSessionEntityType_async", "segments": [ { "end": 51, @@ -15740,28 +17990,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_participants_get_participant_async.py" + "title": "dialogflow_v2_generated_session_entity_types_get_session_entity_type_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflow_v2.ParticipantsClient", - "shortName": "ParticipantsClient" + "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesClient", + "shortName": "SessionEntityTypesClient" }, - "fullName": "google.cloud.dialogflow_v2.ParticipantsClient.get_participant", + "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesClient.get_session_entity_type", "method": { - "fullName": "google.cloud.dialogflow.v2.Participants.GetParticipant", + "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes.GetSessionEntityType", "service": { - "fullName": "google.cloud.dialogflow.v2.Participants", - "shortName": "Participants" + "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes", + "shortName": "SessionEntityTypes" }, - "shortName": "GetParticipant" + "shortName": "GetSessionEntityType" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetParticipantRequest" + "type": "google.cloud.dialogflow_v2.types.GetSessionEntityTypeRequest" }, { "name": "name", @@ -15780,14 +18030,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.types.Participant", - "shortName": "get_participant" + "resultType": "google.cloud.dialogflow_v2.types.SessionEntityType", + "shortName": "get_session_entity_type" }, - "description": "Sample for GetParticipant", - "file": "dialogflow_v2_generated_participants_get_participant_sync.py", + "description": "Sample for GetSessionEntityType", + "file": "dialogflow_v2_generated_session_entity_types_get_session_entity_type_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Participants_GetParticipant_sync", + "regionTag": "dialogflow_v2_generated_SessionEntityTypes_GetSessionEntityType_sync", "segments": [ { "end": 51, @@ -15820,29 +18070,29 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_participants_get_participant_sync.py" + "title": "dialogflow_v2_generated_session_entity_types_get_session_entity_type_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient", - "shortName": "ParticipantsAsyncClient" + "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesAsyncClient", + "shortName": "SessionEntityTypesAsyncClient" }, - "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient.list_participants", + "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesAsyncClient.list_session_entity_types", "method": { - "fullName": "google.cloud.dialogflow.v2.Participants.ListParticipants", + "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes.ListSessionEntityTypes", "service": { - "fullName": "google.cloud.dialogflow.v2.Participants", - "shortName": "Participants" + "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes", + "shortName": "SessionEntityTypes" }, - "shortName": "ListParticipants" + "shortName": "ListSessionEntityTypes" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListParticipantsRequest" + "type": "google.cloud.dialogflow_v2.types.ListSessionEntityTypesRequest" }, { "name": "parent", @@ -15861,14 +18111,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.services.participants.pagers.ListParticipantsAsyncPager", - "shortName": "list_participants" + "resultType": "google.cloud.dialogflow_v2.services.session_entity_types.pagers.ListSessionEntityTypesAsyncPager", + "shortName": "list_session_entity_types" }, - "description": "Sample for ListParticipants", - "file": "dialogflow_v2_generated_participants_list_participants_async.py", + "description": "Sample for ListSessionEntityTypes", + "file": "dialogflow_v2_generated_session_entity_types_list_session_entity_types_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Participants_ListParticipants_async", + "regionTag": "dialogflow_v2_generated_SessionEntityTypes_ListSessionEntityTypes_async", "segments": [ { "end": 52, @@ -15901,28 +18151,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_participants_list_participants_async.py" + "title": "dialogflow_v2_generated_session_entity_types_list_session_entity_types_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflow_v2.ParticipantsClient", - "shortName": "ParticipantsClient" + "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesClient", + "shortName": "SessionEntityTypesClient" }, - "fullName": "google.cloud.dialogflow_v2.ParticipantsClient.list_participants", + "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesClient.list_session_entity_types", "method": { - "fullName": "google.cloud.dialogflow.v2.Participants.ListParticipants", + "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes.ListSessionEntityTypes", "service": { - "fullName": "google.cloud.dialogflow.v2.Participants", - "shortName": "Participants" + "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes", + "shortName": "SessionEntityTypes" }, - "shortName": "ListParticipants" + "shortName": "ListSessionEntityTypes" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListParticipantsRequest" + "type": "google.cloud.dialogflow_v2.types.ListSessionEntityTypesRequest" }, { "name": "parent", @@ -15941,14 +18191,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.services.participants.pagers.ListParticipantsPager", - "shortName": "list_participants" + "resultType": "google.cloud.dialogflow_v2.services.session_entity_types.pagers.ListSessionEntityTypesPager", + "shortName": "list_session_entity_types" }, - "description": "Sample for ListParticipants", - "file": "dialogflow_v2_generated_participants_list_participants_sync.py", + "description": "Sample for ListSessionEntityTypes", + "file": "dialogflow_v2_generated_session_entity_types_list_session_entity_types_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Participants_ListParticipants_sync", + "regionTag": "dialogflow_v2_generated_SessionEntityTypes_ListSessionEntityTypes_sync", "segments": [ { "end": 52, @@ -15981,29 +18231,37 @@ "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_participants_list_participants_sync.py" + "title": "dialogflow_v2_generated_session_entity_types_list_session_entity_types_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient", - "shortName": "ParticipantsAsyncClient" + "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesAsyncClient", + "shortName": "SessionEntityTypesAsyncClient" }, - "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient.streaming_analyze_content", + "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesAsyncClient.update_session_entity_type", "method": { - "fullName": "google.cloud.dialogflow.v2.Participants.StreamingAnalyzeContent", + "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes.UpdateSessionEntityType", "service": { - "fullName": "google.cloud.dialogflow.v2.Participants", - "shortName": "Participants" + "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes", + "shortName": "SessionEntityTypes" }, - "shortName": "StreamingAnalyzeContent" + "shortName": "UpdateSessionEntityType" }, "parameters": [ { - "name": "requests", - "type": "Iterator[google.cloud.dialogflow_v2.types.StreamingAnalyzeContentRequest]" + "name": "request", + "type": "google.cloud.dialogflow_v2.types.UpdateSessionEntityTypeRequest" + }, + { + "name": "session_entity_type", + "type": "google.cloud.dialogflow_v2.types.SessionEntityType" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -16018,22 +18276,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "Iterable[google.cloud.dialogflow_v2.types.StreamingAnalyzeContentResponse]", - "shortName": "streaming_analyze_content" + "resultType": "google.cloud.dialogflow_v2.types.SessionEntityType", + "shortName": "update_session_entity_type" }, - "description": "Sample for StreamingAnalyzeContent", - "file": "dialogflow_v2_generated_participants_streaming_analyze_content_async.py", + "description": "Sample for UpdateSessionEntityType", + "file": "dialogflow_v2_generated_session_entity_types_update_session_entity_type_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Participants_StreamingAnalyzeContent_async", + "regionTag": "dialogflow_v2_generated_SessionEntityTypes_UpdateSessionEntityType_async", "segments": [ { - "end": 69, + "end": 57, "start": 27, "type": "FULL" }, { - "end": 69, + "end": 57, "start": 27, "type": "SHORT" }, @@ -16043,43 +18301,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 62, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 65, - "start": 63, + "end": 54, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 70, - "start": 66, + "end": 58, + "start": 55, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_participants_streaming_analyze_content_async.py" + "title": "dialogflow_v2_generated_session_entity_types_update_session_entity_type_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflow_v2.ParticipantsClient", - "shortName": "ParticipantsClient" + "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesClient", + "shortName": "SessionEntityTypesClient" }, - "fullName": "google.cloud.dialogflow_v2.ParticipantsClient.streaming_analyze_content", + "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesClient.update_session_entity_type", "method": { - "fullName": "google.cloud.dialogflow.v2.Participants.StreamingAnalyzeContent", + "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes.UpdateSessionEntityType", "service": { - "fullName": "google.cloud.dialogflow.v2.Participants", - "shortName": "Participants" + "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes", + "shortName": "SessionEntityTypes" }, - "shortName": "StreamingAnalyzeContent" + "shortName": "UpdateSessionEntityType" }, "parameters": [ { - "name": "requests", - "type": "Iterator[google.cloud.dialogflow_v2.types.StreamingAnalyzeContentRequest]" + "name": "request", + "type": "google.cloud.dialogflow_v2.types.UpdateSessionEntityTypeRequest" + }, + { + "name": "session_entity_type", + "type": "google.cloud.dialogflow_v2.types.SessionEntityType" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -16094,22 +18360,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "Iterable[google.cloud.dialogflow_v2.types.StreamingAnalyzeContentResponse]", - "shortName": "streaming_analyze_content" + "resultType": "google.cloud.dialogflow_v2.types.SessionEntityType", + "shortName": "update_session_entity_type" }, - "description": "Sample for StreamingAnalyzeContent", - "file": "dialogflow_v2_generated_participants_streaming_analyze_content_sync.py", + "description": "Sample for UpdateSessionEntityType", + "file": "dialogflow_v2_generated_session_entity_types_update_session_entity_type_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Participants_StreamingAnalyzeContent_sync", + "regionTag": "dialogflow_v2_generated_SessionEntityTypes_UpdateSessionEntityType_sync", "segments": [ { - "end": 69, + "end": 57, "start": 27, "type": "FULL" }, { - "end": 69, + "end": 57, "start": 27, "type": "SHORT" }, @@ -16119,49 +18385,53 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 62, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 65, - "start": 63, + "end": 54, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 70, - "start": 66, + "end": 58, + "start": 55, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_participants_streaming_analyze_content_sync.py" + "title": "dialogflow_v2_generated_session_entity_types_update_session_entity_type_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient", - "shortName": "ParticipantsAsyncClient" + "fullName": "google.cloud.dialogflow_v2.SessionsAsyncClient", + "shortName": "SessionsAsyncClient" }, - "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient.suggest_articles", + "fullName": "google.cloud.dialogflow_v2.SessionsAsyncClient.detect_intent", "method": { - "fullName": "google.cloud.dialogflow.v2.Participants.SuggestArticles", + "fullName": "google.cloud.dialogflow.v2.Sessions.DetectIntent", "service": { - "fullName": "google.cloud.dialogflow.v2.Participants", - "shortName": "Participants" + "fullName": "google.cloud.dialogflow.v2.Sessions", + "shortName": "Sessions" }, - "shortName": "SuggestArticles" + "shortName": "DetectIntent" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.SuggestArticlesRequest" + "type": "google.cloud.dialogflow_v2.types.DetectIntentRequest" }, { - "name": "parent", + "name": "session", "type": "str" }, + { + "name": "query_input", + "type": "google.cloud.dialogflow_v2.types.QueryInput" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -16175,22 +18445,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.types.SuggestArticlesResponse", - "shortName": "suggest_articles" + "resultType": "google.cloud.dialogflow_v2.types.DetectIntentResponse", + "shortName": "detect_intent" }, - "description": "Sample for SuggestArticles", - "file": "dialogflow_v2_generated_participants_suggest_articles_async.py", + "description": "Sample for DetectIntent", + "file": "dialogflow_v2_generated_sessions_detect_intent_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Participants_SuggestArticles_async", + "regionTag": "dialogflow_v2_generated_Sessions_DetectIntent_async", "segments": [ { - "end": 51, + "end": 57, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 57, "start": 27, "type": "SHORT" }, @@ -16200,48 +18470,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 54, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 58, + "start": 55, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_participants_suggest_articles_async.py" + "title": "dialogflow_v2_generated_sessions_detect_intent_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflow_v2.ParticipantsClient", - "shortName": "ParticipantsClient" + "fullName": "google.cloud.dialogflow_v2.SessionsClient", + "shortName": "SessionsClient" }, - "fullName": "google.cloud.dialogflow_v2.ParticipantsClient.suggest_articles", + "fullName": "google.cloud.dialogflow_v2.SessionsClient.detect_intent", "method": { - "fullName": "google.cloud.dialogflow.v2.Participants.SuggestArticles", + "fullName": "google.cloud.dialogflow.v2.Sessions.DetectIntent", "service": { - "fullName": "google.cloud.dialogflow.v2.Participants", - "shortName": "Participants" + "fullName": "google.cloud.dialogflow.v2.Sessions", + "shortName": "Sessions" }, - "shortName": "SuggestArticles" + "shortName": "DetectIntent" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.SuggestArticlesRequest" + "type": "google.cloud.dialogflow_v2.types.DetectIntentRequest" }, { - "name": "parent", + "name": "session", "type": "str" }, + { + "name": "query_input", + "type": "google.cloud.dialogflow_v2.types.QueryInput" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -16255,22 +18529,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.types.SuggestArticlesResponse", - "shortName": "suggest_articles" + "resultType": "google.cloud.dialogflow_v2.types.DetectIntentResponse", + "shortName": "detect_intent" }, - "description": "Sample for SuggestArticles", - "file": "dialogflow_v2_generated_participants_suggest_articles_sync.py", + "description": "Sample for DetectIntent", + "file": "dialogflow_v2_generated_sessions_detect_intent_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Participants_SuggestArticles_sync", + "regionTag": "dialogflow_v2_generated_Sessions_DetectIntent_sync", "segments": [ { - "end": 51, + "end": 57, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 57, "start": 27, "type": "SHORT" }, @@ -16280,48 +18554,44 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 54, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 58, + "start": 55, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_participants_suggest_articles_sync.py" + "title": "dialogflow_v2_generated_sessions_detect_intent_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient", - "shortName": "ParticipantsAsyncClient" + "fullName": "google.cloud.dialogflow_v2.SessionsAsyncClient", + "shortName": "SessionsAsyncClient" }, - "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient.suggest_faq_answers", + "fullName": "google.cloud.dialogflow_v2.SessionsAsyncClient.streaming_detect_intent", "method": { - "fullName": "google.cloud.dialogflow.v2.Participants.SuggestFaqAnswers", + "fullName": "google.cloud.dialogflow.v2.Sessions.StreamingDetectIntent", "service": { - "fullName": "google.cloud.dialogflow.v2.Participants", - "shortName": "Participants" + "fullName": "google.cloud.dialogflow.v2.Sessions", + "shortName": "Sessions" }, - "shortName": "SuggestFaqAnswers" + "shortName": "StreamingDetectIntent" }, "parameters": [ { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.SuggestFaqAnswersRequest" - }, - { - "name": "parent", - "type": "str" + "name": "requests", + "type": "Iterator[google.cloud.dialogflow_v2.types.StreamingDetectIntentRequest]" }, { "name": "retry", @@ -16336,22 +18606,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.types.SuggestFaqAnswersResponse", - "shortName": "suggest_faq_answers" + "resultType": "Iterable[google.cloud.dialogflow_v2.types.StreamingDetectIntentResponse]", + "shortName": "streaming_detect_intent" }, - "description": "Sample for SuggestFaqAnswers", - "file": "dialogflow_v2_generated_participants_suggest_faq_answers_async.py", + "description": "Sample for StreamingDetectIntent", + "file": "dialogflow_v2_generated_sessions_streaming_detect_intent_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Participants_SuggestFaqAnswers_async", + "regionTag": "dialogflow_v2_generated_Sessions_StreamingDetectIntent_async", "segments": [ { - "end": 51, + "end": 68, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 68, "start": 27, "type": "SHORT" }, @@ -16361,47 +18631,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 61, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 64, + "start": 62, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 69, + "start": 65, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_participants_suggest_faq_answers_async.py" + "title": "dialogflow_v2_generated_sessions_streaming_detect_intent_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflow_v2.ParticipantsClient", - "shortName": "ParticipantsClient" + "fullName": "google.cloud.dialogflow_v2.SessionsClient", + "shortName": "SessionsClient" }, - "fullName": "google.cloud.dialogflow_v2.ParticipantsClient.suggest_faq_answers", + "fullName": "google.cloud.dialogflow_v2.SessionsClient.streaming_detect_intent", "method": { - "fullName": "google.cloud.dialogflow.v2.Participants.SuggestFaqAnswers", + "fullName": "google.cloud.dialogflow.v2.Sessions.StreamingDetectIntent", "service": { - "fullName": "google.cloud.dialogflow.v2.Participants", - "shortName": "Participants" + "fullName": "google.cloud.dialogflow.v2.Sessions", + "shortName": "Sessions" }, - "shortName": "SuggestFaqAnswers" + "shortName": "StreamingDetectIntent" }, "parameters": [ { - "name": "request", - "type": "google.cloud.dialogflow_v2.types.SuggestFaqAnswersRequest" - }, - { - "name": "parent", - "type": "str" + "name": "requests", + "type": "Iterator[google.cloud.dialogflow_v2.types.StreamingDetectIntentRequest]" }, { "name": "retry", @@ -16416,22 +18682,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.types.SuggestFaqAnswersResponse", - "shortName": "suggest_faq_answers" + "resultType": "Iterable[google.cloud.dialogflow_v2.types.StreamingDetectIntentResponse]", + "shortName": "streaming_detect_intent" }, - "description": "Sample for SuggestFaqAnswers", - "file": "dialogflow_v2_generated_participants_suggest_faq_answers_sync.py", + "description": "Sample for StreamingDetectIntent", + "file": "dialogflow_v2_generated_sessions_streaming_detect_intent_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Participants_SuggestFaqAnswers_sync", + "regionTag": "dialogflow_v2_generated_Sessions_StreamingDetectIntent_sync", "segments": [ { - "end": 51, + "end": 68, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 68, "start": 27, "type": "SHORT" }, @@ -16441,44 +18707,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 61, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 64, + "start": 62, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 69, + "start": 65, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_participants_suggest_faq_answers_sync.py" + "title": "dialogflow_v2_generated_sessions_streaming_detect_intent_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient", - "shortName": "ParticipantsAsyncClient" + "fullName": "google.cloud.dialogflow_v2.SipTrunksAsyncClient", + "shortName": "SipTrunksAsyncClient" }, - "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient.suggest_knowledge_assist", + "fullName": "google.cloud.dialogflow_v2.SipTrunksAsyncClient.create_sip_trunk", "method": { - "fullName": "google.cloud.dialogflow.v2.Participants.SuggestKnowledgeAssist", + "fullName": "google.cloud.dialogflow.v2.SipTrunks.CreateSipTrunk", "service": { - "fullName": "google.cloud.dialogflow.v2.Participants", - "shortName": "Participants" + "fullName": "google.cloud.dialogflow.v2.SipTrunks", + "shortName": "SipTrunks" }, - "shortName": "SuggestKnowledgeAssist" + "shortName": "CreateSipTrunk" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.SuggestKnowledgeAssistRequest" + "type": "google.cloud.dialogflow_v2.types.CreateSipTrunkRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "sip_trunk", + "type": "google.cloud.dialogflow_v2.types.SipTrunk" }, { "name": "retry", @@ -16493,22 +18767,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.types.SuggestKnowledgeAssistResponse", - "shortName": "suggest_knowledge_assist" + "resultType": "google.cloud.dialogflow_v2.types.SipTrunk", + "shortName": "create_sip_trunk" }, - "description": "Sample for SuggestKnowledgeAssist", - "file": "dialogflow_v2_generated_participants_suggest_knowledge_assist_async.py", + "description": "Sample for CreateSipTrunk", + "file": "dialogflow_v2_generated_sip_trunks_create_sip_trunk_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Participants_SuggestKnowledgeAssist_async", + "regionTag": "dialogflow_v2_generated_SipTrunks_CreateSipTrunk_async", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -16518,43 +18792,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_participants_suggest_knowledge_assist_async.py" + "title": "dialogflow_v2_generated_sip_trunks_create_sip_trunk_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflow_v2.ParticipantsClient", - "shortName": "ParticipantsClient" + "fullName": "google.cloud.dialogflow_v2.SipTrunksClient", + "shortName": "SipTrunksClient" }, - "fullName": "google.cloud.dialogflow_v2.ParticipantsClient.suggest_knowledge_assist", + "fullName": "google.cloud.dialogflow_v2.SipTrunksClient.create_sip_trunk", "method": { - "fullName": "google.cloud.dialogflow.v2.Participants.SuggestKnowledgeAssist", + "fullName": "google.cloud.dialogflow.v2.SipTrunks.CreateSipTrunk", "service": { - "fullName": "google.cloud.dialogflow.v2.Participants", - "shortName": "Participants" + "fullName": "google.cloud.dialogflow.v2.SipTrunks", + "shortName": "SipTrunks" }, - "shortName": "SuggestKnowledgeAssist" + "shortName": "CreateSipTrunk" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.SuggestKnowledgeAssistRequest" + "type": "google.cloud.dialogflow_v2.types.CreateSipTrunkRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "sip_trunk", + "type": "google.cloud.dialogflow_v2.types.SipTrunk" }, { "name": "retry", @@ -16569,22 +18851,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.types.SuggestKnowledgeAssistResponse", - "shortName": "suggest_knowledge_assist" + "resultType": "google.cloud.dialogflow_v2.types.SipTrunk", + "shortName": "create_sip_trunk" }, - "description": "Sample for SuggestKnowledgeAssist", - "file": "dialogflow_v2_generated_participants_suggest_knowledge_assist_sync.py", + "description": "Sample for CreateSipTrunk", + "file": "dialogflow_v2_generated_sip_trunks_create_sip_trunk_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Participants_SuggestKnowledgeAssist_sync", + "regionTag": "dialogflow_v2_generated_SipTrunks_CreateSipTrunk_sync", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -16594,47 +18876,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_participants_suggest_knowledge_assist_sync.py" + "title": "dialogflow_v2_generated_sip_trunks_create_sip_trunk_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient", - "shortName": "ParticipantsAsyncClient" + "fullName": "google.cloud.dialogflow_v2.SipTrunksAsyncClient", + "shortName": "SipTrunksAsyncClient" }, - "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient.suggest_smart_replies", + "fullName": "google.cloud.dialogflow_v2.SipTrunksAsyncClient.delete_sip_trunk", "method": { - "fullName": "google.cloud.dialogflow.v2.Participants.SuggestSmartReplies", + "fullName": "google.cloud.dialogflow.v2.SipTrunks.DeleteSipTrunk", "service": { - "fullName": "google.cloud.dialogflow.v2.Participants", - "shortName": "Participants" + "fullName": "google.cloud.dialogflow.v2.SipTrunks", + "shortName": "SipTrunks" }, - "shortName": "SuggestSmartReplies" + "shortName": "DeleteSipTrunk" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.SuggestSmartRepliesRequest" + "type": "google.cloud.dialogflow_v2.types.DeleteSipTrunkRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -16650,22 +18932,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.types.SuggestSmartRepliesResponse", - "shortName": "suggest_smart_replies" + "shortName": "delete_sip_trunk" }, - "description": "Sample for SuggestSmartReplies", - "file": "dialogflow_v2_generated_participants_suggest_smart_replies_async.py", + "description": "Sample for DeleteSipTrunk", + "file": "dialogflow_v2_generated_sip_trunks_delete_sip_trunk_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Participants_SuggestSmartReplies_async", + "regionTag": "dialogflow_v2_generated_SipTrunks_DeleteSipTrunk_async", "segments": [ { - "end": 51, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 49, "start": 27, "type": "SHORT" }, @@ -16680,41 +18961,39 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_participants_suggest_smart_replies_async.py" + "title": "dialogflow_v2_generated_sip_trunks_delete_sip_trunk_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflow_v2.ParticipantsClient", - "shortName": "ParticipantsClient" + "fullName": "google.cloud.dialogflow_v2.SipTrunksClient", + "shortName": "SipTrunksClient" }, - "fullName": "google.cloud.dialogflow_v2.ParticipantsClient.suggest_smart_replies", + "fullName": "google.cloud.dialogflow_v2.SipTrunksClient.delete_sip_trunk", "method": { - "fullName": "google.cloud.dialogflow.v2.Participants.SuggestSmartReplies", + "fullName": "google.cloud.dialogflow.v2.SipTrunks.DeleteSipTrunk", "service": { - "fullName": "google.cloud.dialogflow.v2.Participants", - "shortName": "Participants" + "fullName": "google.cloud.dialogflow.v2.SipTrunks", + "shortName": "SipTrunks" }, - "shortName": "SuggestSmartReplies" + "shortName": "DeleteSipTrunk" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.SuggestSmartRepliesRequest" + "type": "google.cloud.dialogflow_v2.types.DeleteSipTrunkRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -16730,22 +19009,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.types.SuggestSmartRepliesResponse", - "shortName": "suggest_smart_replies" + "shortName": "delete_sip_trunk" }, - "description": "Sample for SuggestSmartReplies", - "file": "dialogflow_v2_generated_participants_suggest_smart_replies_sync.py", + "description": "Sample for DeleteSipTrunk", + "file": "dialogflow_v2_generated_sip_trunks_delete_sip_trunk_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Participants_SuggestSmartReplies_sync", + "regionTag": "dialogflow_v2_generated_SipTrunks_DeleteSipTrunk_sync", "segments": [ { - "end": 51, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 49, "start": 27, "type": "SHORT" }, @@ -16760,47 +19038,41 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_participants_suggest_smart_replies_sync.py" + "title": "dialogflow_v2_generated_sip_trunks_delete_sip_trunk_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient", - "shortName": "ParticipantsAsyncClient" + "fullName": "google.cloud.dialogflow_v2.SipTrunksAsyncClient", + "shortName": "SipTrunksAsyncClient" }, - "fullName": "google.cloud.dialogflow_v2.ParticipantsAsyncClient.update_participant", + "fullName": "google.cloud.dialogflow_v2.SipTrunksAsyncClient.get_sip_trunk", "method": { - "fullName": "google.cloud.dialogflow.v2.Participants.UpdateParticipant", + "fullName": "google.cloud.dialogflow.v2.SipTrunks.GetSipTrunk", "service": { - "fullName": "google.cloud.dialogflow.v2.Participants", - "shortName": "Participants" + "fullName": "google.cloud.dialogflow.v2.SipTrunks", + "shortName": "SipTrunks" }, - "shortName": "UpdateParticipant" + "shortName": "GetSipTrunk" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.UpdateParticipantRequest" + "type": "google.cloud.dialogflow_v2.types.GetSipTrunkRequest" }, { - "name": "participant", - "type": "google.cloud.dialogflow_v2.types.Participant" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "name", + "type": "str" }, { "name": "retry", @@ -16815,22 +19087,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.types.Participant", - "shortName": "update_participant" + "resultType": "google.cloud.dialogflow_v2.types.SipTrunk", + "shortName": "get_sip_trunk" }, - "description": "Sample for UpdateParticipant", - "file": "dialogflow_v2_generated_participants_update_participant_async.py", + "description": "Sample for GetSipTrunk", + "file": "dialogflow_v2_generated_sip_trunks_get_sip_trunk_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Participants_UpdateParticipant_async", + "regionTag": "dialogflow_v2_generated_SipTrunks_GetSipTrunk_async", "segments": [ { - "end": 50, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 50, + "end": 51, "start": 27, "type": "SHORT" }, @@ -16840,51 +19112,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 44, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 47, - "start": 45, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 51, - "start": 48, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_participants_update_participant_async.py" + "title": "dialogflow_v2_generated_sip_trunks_get_sip_trunk_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflow_v2.ParticipantsClient", - "shortName": "ParticipantsClient" + "fullName": "google.cloud.dialogflow_v2.SipTrunksClient", + "shortName": "SipTrunksClient" }, - "fullName": "google.cloud.dialogflow_v2.ParticipantsClient.update_participant", + "fullName": "google.cloud.dialogflow_v2.SipTrunksClient.get_sip_trunk", "method": { - "fullName": "google.cloud.dialogflow.v2.Participants.UpdateParticipant", + "fullName": "google.cloud.dialogflow.v2.SipTrunks.GetSipTrunk", "service": { - "fullName": "google.cloud.dialogflow.v2.Participants", - "shortName": "Participants" + "fullName": "google.cloud.dialogflow.v2.SipTrunks", + "shortName": "SipTrunks" }, - "shortName": "UpdateParticipant" + "shortName": "GetSipTrunk" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.UpdateParticipantRequest" - }, - { - "name": "participant", - "type": "google.cloud.dialogflow_v2.types.Participant" + "type": "google.cloud.dialogflow_v2.types.GetSipTrunkRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "name", + "type": "str" }, { "name": "retry", @@ -16899,22 +19167,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.types.Participant", - "shortName": "update_participant" + "resultType": "google.cloud.dialogflow_v2.types.SipTrunk", + "shortName": "get_sip_trunk" }, - "description": "Sample for UpdateParticipant", - "file": "dialogflow_v2_generated_participants_update_participant_sync.py", + "description": "Sample for GetSipTrunk", + "file": "dialogflow_v2_generated_sip_trunks_get_sip_trunk_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Participants_UpdateParticipant_sync", + "regionTag": "dialogflow_v2_generated_SipTrunks_GetSipTrunk_sync", "segments": [ { - "end": 50, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 50, + "end": 51, "start": 27, "type": "SHORT" }, @@ -16924,53 +19192,49 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 44, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 47, - "start": 45, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 51, - "start": 48, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_participants_update_participant_sync.py" + "title": "dialogflow_v2_generated_sip_trunks_get_sip_trunk_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesAsyncClient", - "shortName": "SessionEntityTypesAsyncClient" + "fullName": "google.cloud.dialogflow_v2.SipTrunksAsyncClient", + "shortName": "SipTrunksAsyncClient" }, - "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesAsyncClient.create_session_entity_type", + "fullName": "google.cloud.dialogflow_v2.SipTrunksAsyncClient.list_sip_trunks", "method": { - "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes.CreateSessionEntityType", + "fullName": "google.cloud.dialogflow.v2.SipTrunks.ListSipTrunks", "service": { - "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes", - "shortName": "SessionEntityTypes" + "fullName": "google.cloud.dialogflow.v2.SipTrunks", + "shortName": "SipTrunks" }, - "shortName": "CreateSessionEntityType" + "shortName": "ListSipTrunks" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.CreateSessionEntityTypeRequest" + "type": "google.cloud.dialogflow_v2.types.ListSipTrunksRequest" }, { "name": "parent", "type": "str" }, - { - "name": "session_entity_type", - "type": "google.cloud.dialogflow_v2.types.SessionEntityType" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -16984,22 +19248,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.types.SessionEntityType", - "shortName": "create_session_entity_type" + "resultType": "google.cloud.dialogflow_v2.services.sip_trunks.pagers.ListSipTrunksAsyncPager", + "shortName": "list_sip_trunks" }, - "description": "Sample for CreateSessionEntityType", - "file": "dialogflow_v2_generated_session_entity_types_create_session_entity_type_async.py", + "description": "Sample for ListSipTrunks", + "file": "dialogflow_v2_generated_sip_trunks_list_sip_trunks_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_SessionEntityTypes_CreateSessionEntityType_async", + "regionTag": "dialogflow_v2_generated_SipTrunks_ListSipTrunks_async", "segments": [ { - "end": 58, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 58, + "end": 52, "start": 27, "type": "SHORT" }, @@ -17009,52 +19273,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 52, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 55, - "start": 53, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 59, - "start": 56, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_session_entity_types_create_session_entity_type_async.py" + "title": "dialogflow_v2_generated_sip_trunks_list_sip_trunks_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesClient", - "shortName": "SessionEntityTypesClient" + "fullName": "google.cloud.dialogflow_v2.SipTrunksClient", + "shortName": "SipTrunksClient" }, - "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesClient.create_session_entity_type", + "fullName": "google.cloud.dialogflow_v2.SipTrunksClient.list_sip_trunks", "method": { - "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes.CreateSessionEntityType", + "fullName": "google.cloud.dialogflow.v2.SipTrunks.ListSipTrunks", "service": { - "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes", - "shortName": "SessionEntityTypes" + "fullName": "google.cloud.dialogflow.v2.SipTrunks", + "shortName": "SipTrunks" }, - "shortName": "CreateSessionEntityType" + "shortName": "ListSipTrunks" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.CreateSessionEntityTypeRequest" + "type": "google.cloud.dialogflow_v2.types.ListSipTrunksRequest" }, { "name": "parent", "type": "str" }, - { - "name": "session_entity_type", - "type": "google.cloud.dialogflow_v2.types.SessionEntityType" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -17068,22 +19328,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.types.SessionEntityType", - "shortName": "create_session_entity_type" + "resultType": "google.cloud.dialogflow_v2.services.sip_trunks.pagers.ListSipTrunksPager", + "shortName": "list_sip_trunks" }, - "description": "Sample for CreateSessionEntityType", - "file": "dialogflow_v2_generated_session_entity_types_create_session_entity_type_sync.py", + "description": "Sample for ListSipTrunks", + "file": "dialogflow_v2_generated_sip_trunks_list_sip_trunks_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_SessionEntityTypes_CreateSessionEntityType_sync", + "regionTag": "dialogflow_v2_generated_SipTrunks_ListSipTrunks_sync", "segments": [ { - "end": 58, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 58, + "end": 52, "start": 27, "type": "SHORT" }, @@ -17093,48 +19353,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 52, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 55, - "start": 53, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 59, - "start": 56, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_session_entity_types_create_session_entity_type_sync.py" + "title": "dialogflow_v2_generated_sip_trunks_list_sip_trunks_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesAsyncClient", - "shortName": "SessionEntityTypesAsyncClient" + "fullName": "google.cloud.dialogflow_v2.SipTrunksAsyncClient", + "shortName": "SipTrunksAsyncClient" }, - "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesAsyncClient.delete_session_entity_type", + "fullName": "google.cloud.dialogflow_v2.SipTrunksAsyncClient.update_sip_trunk", "method": { - "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes.DeleteSessionEntityType", + "fullName": "google.cloud.dialogflow.v2.SipTrunks.UpdateSipTrunk", "service": { - "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes", - "shortName": "SessionEntityTypes" + "fullName": "google.cloud.dialogflow.v2.SipTrunks", + "shortName": "SipTrunks" }, - "shortName": "DeleteSessionEntityType" + "shortName": "UpdateSipTrunk" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.DeleteSessionEntityTypeRequest" + "type": "google.cloud.dialogflow_v2.types.UpdateSipTrunkRequest" }, { - "name": "name", - "type": "str" + "name": "sip_trunk", + "type": "google.cloud.dialogflow_v2.types.SipTrunk" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -17149,21 +19413,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_session_entity_type" + "resultType": "google.cloud.dialogflow_v2.types.SipTrunk", + "shortName": "update_sip_trunk" }, - "description": "Sample for DeleteSessionEntityType", - "file": "dialogflow_v2_generated_session_entity_types_delete_session_entity_type_async.py", + "description": "Sample for UpdateSipTrunk", + "file": "dialogflow_v2_generated_sip_trunks_update_sip_trunk_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_SessionEntityTypes_DeleteSessionEntityType_async", + "regionTag": "dialogflow_v2_generated_SipTrunks_UpdateSipTrunk_async", "segments": [ { - "end": 49, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 54, "start": 27, "type": "SHORT" }, @@ -17173,45 +19438,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "start": 46, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_session_entity_types_delete_session_entity_type_async.py" + "title": "dialogflow_v2_generated_sip_trunks_update_sip_trunk_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesClient", - "shortName": "SessionEntityTypesClient" + "fullName": "google.cloud.dialogflow_v2.SipTrunksClient", + "shortName": "SipTrunksClient" }, - "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesClient.delete_session_entity_type", + "fullName": "google.cloud.dialogflow_v2.SipTrunksClient.update_sip_trunk", "method": { - "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes.DeleteSessionEntityType", + "fullName": "google.cloud.dialogflow.v2.SipTrunks.UpdateSipTrunk", "service": { - "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes", - "shortName": "SessionEntityTypes" + "fullName": "google.cloud.dialogflow.v2.SipTrunks", + "shortName": "SipTrunks" }, - "shortName": "DeleteSessionEntityType" + "shortName": "UpdateSipTrunk" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.DeleteSessionEntityTypeRequest" + "type": "google.cloud.dialogflow_v2.types.UpdateSipTrunkRequest" }, { - "name": "name", - "type": "str" + "name": "sip_trunk", + "type": "google.cloud.dialogflow_v2.types.SipTrunk" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -17226,21 +19497,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "shortName": "delete_session_entity_type" + "resultType": "google.cloud.dialogflow_v2.types.SipTrunk", + "shortName": "update_sip_trunk" }, - "description": "Sample for DeleteSessionEntityType", - "file": "dialogflow_v2_generated_session_entity_types_delete_session_entity_type_sync.py", + "description": "Sample for UpdateSipTrunk", + "file": "dialogflow_v2_generated_sip_trunks_update_sip_trunk_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_SessionEntityTypes_DeleteSessionEntityType_sync", + "regionTag": "dialogflow_v2_generated_SipTrunks_UpdateSipTrunk_sync", "segments": [ { - "end": 49, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 49, + "end": 54, "start": 27, "type": "SHORT" }, @@ -17250,45 +19522,55 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "start": 46, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 50, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_session_entity_types_delete_session_entity_type_sync.py" + "title": "dialogflow_v2_generated_sip_trunks_update_sip_trunk_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesAsyncClient", - "shortName": "SessionEntityTypesAsyncClient" + "fullName": "google.cloud.dialogflow_v2.ToolsAsyncClient", + "shortName": "ToolsAsyncClient" }, - "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesAsyncClient.get_session_entity_type", + "fullName": "google.cloud.dialogflow_v2.ToolsAsyncClient.create_tool", "method": { - "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes.GetSessionEntityType", + "fullName": "google.cloud.dialogflow.v2.Tools.CreateTool", "service": { - "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes", - "shortName": "SessionEntityTypes" + "fullName": "google.cloud.dialogflow.v2.Tools", + "shortName": "Tools" }, - "shortName": "GetSessionEntityType" + "shortName": "CreateTool" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetSessionEntityTypeRequest" + "type": "google.cloud.dialogflow_v2.types.CreateToolRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "tool", + "type": "google.cloud.dialogflow_v2.types.Tool" + }, + { + "name": "tool_id", "type": "str" }, { @@ -17304,22 +19586,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.types.SessionEntityType", - "shortName": "get_session_entity_type" + "resultType": "google.cloud.dialogflow_v2.types.Tool", + "shortName": "create_tool" }, - "description": "Sample for GetSessionEntityType", - "file": "dialogflow_v2_generated_session_entity_types_get_session_entity_type_async.py", + "description": "Sample for CreateTool", + "file": "dialogflow_v2_generated_tools_create_tool_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_SessionEntityTypes_GetSessionEntityType_async", + "regionTag": "dialogflow_v2_generated_Tools_CreateTool_async", "segments": [ { - "end": 51, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 56, "start": 27, "type": "SHORT" }, @@ -17329,46 +19611,54 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 53, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_session_entity_types_get_session_entity_type_async.py" + "title": "dialogflow_v2_generated_tools_create_tool_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesClient", - "shortName": "SessionEntityTypesClient" + "fullName": "google.cloud.dialogflow_v2.ToolsClient", + "shortName": "ToolsClient" }, - "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesClient.get_session_entity_type", + "fullName": "google.cloud.dialogflow_v2.ToolsClient.create_tool", "method": { - "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes.GetSessionEntityType", + "fullName": "google.cloud.dialogflow.v2.Tools.CreateTool", "service": { - "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes", - "shortName": "SessionEntityTypes" + "fullName": "google.cloud.dialogflow.v2.Tools", + "shortName": "Tools" }, - "shortName": "GetSessionEntityType" + "shortName": "CreateTool" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.GetSessionEntityTypeRequest" + "type": "google.cloud.dialogflow_v2.types.CreateToolRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "tool", + "type": "google.cloud.dialogflow_v2.types.Tool" + }, + { + "name": "tool_id", "type": "str" }, { @@ -17384,22 +19674,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.types.SessionEntityType", - "shortName": "get_session_entity_type" + "resultType": "google.cloud.dialogflow_v2.types.Tool", + "shortName": "create_tool" }, - "description": "Sample for GetSessionEntityType", - "file": "dialogflow_v2_generated_session_entity_types_get_session_entity_type_sync.py", + "description": "Sample for CreateTool", + "file": "dialogflow_v2_generated_tools_create_tool_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_SessionEntityTypes_GetSessionEntityType_sync", + "regionTag": "dialogflow_v2_generated_Tools_CreateTool_sync", "segments": [ { - "end": 51, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 56, "start": 27, "type": "SHORT" }, @@ -17409,47 +19699,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 53, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_session_entity_types_get_session_entity_type_sync.py" + "title": "dialogflow_v2_generated_tools_create_tool_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesAsyncClient", - "shortName": "SessionEntityTypesAsyncClient" + "fullName": "google.cloud.dialogflow_v2.ToolsAsyncClient", + "shortName": "ToolsAsyncClient" }, - "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesAsyncClient.list_session_entity_types", + "fullName": "google.cloud.dialogflow_v2.ToolsAsyncClient.delete_tool", "method": { - "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes.ListSessionEntityTypes", + "fullName": "google.cloud.dialogflow.v2.Tools.DeleteTool", "service": { - "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes", - "shortName": "SessionEntityTypes" + "fullName": "google.cloud.dialogflow.v2.Tools", + "shortName": "Tools" }, - "shortName": "ListSessionEntityTypes" + "shortName": "DeleteTool" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListSessionEntityTypesRequest" + "type": "google.cloud.dialogflow_v2.types.DeleteToolRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -17465,22 +19755,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.services.session_entity_types.pagers.ListSessionEntityTypesAsyncPager", - "shortName": "list_session_entity_types" + "shortName": "delete_tool" }, - "description": "Sample for ListSessionEntityTypes", - "file": "dialogflow_v2_generated_session_entity_types_list_session_entity_types_async.py", + "description": "Sample for DeleteTool", + "file": "dialogflow_v2_generated_tools_delete_tool_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_SessionEntityTypes_ListSessionEntityTypes_async", + "regionTag": "dialogflow_v2_generated_Tools_DeleteTool_async", "segments": [ { - "end": 52, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 49, "start": 27, "type": "SHORT" }, @@ -17495,41 +19784,39 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_session_entity_types_list_session_entity_types_async.py" + "title": "dialogflow_v2_generated_tools_delete_tool_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesClient", - "shortName": "SessionEntityTypesClient" + "fullName": "google.cloud.dialogflow_v2.ToolsClient", + "shortName": "ToolsClient" }, - "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesClient.list_session_entity_types", + "fullName": "google.cloud.dialogflow_v2.ToolsClient.delete_tool", "method": { - "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes.ListSessionEntityTypes", + "fullName": "google.cloud.dialogflow.v2.Tools.DeleteTool", "service": { - "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes", - "shortName": "SessionEntityTypes" + "fullName": "google.cloud.dialogflow.v2.Tools", + "shortName": "Tools" }, - "shortName": "ListSessionEntityTypes" + "shortName": "DeleteTool" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.ListSessionEntityTypesRequest" + "type": "google.cloud.dialogflow_v2.types.DeleteToolRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -17545,22 +19832,21 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.services.session_entity_types.pagers.ListSessionEntityTypesPager", - "shortName": "list_session_entity_types" + "shortName": "delete_tool" }, - "description": "Sample for ListSessionEntityTypes", - "file": "dialogflow_v2_generated_session_entity_types_list_session_entity_types_sync.py", + "description": "Sample for DeleteTool", + "file": "dialogflow_v2_generated_tools_delete_tool_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_SessionEntityTypes_ListSessionEntityTypes_sync", + "regionTag": "dialogflow_v2_generated_Tools_DeleteTool_sync", "segments": [ { - "end": 52, + "end": 49, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 49, "start": 27, "type": "SHORT" }, @@ -17575,47 +19861,41 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 50, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_session_entity_types_list_session_entity_types_sync.py" + "title": "dialogflow_v2_generated_tools_delete_tool_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesAsyncClient", - "shortName": "SessionEntityTypesAsyncClient" + "fullName": "google.cloud.dialogflow_v2.ToolsAsyncClient", + "shortName": "ToolsAsyncClient" }, - "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesAsyncClient.update_session_entity_type", + "fullName": "google.cloud.dialogflow_v2.ToolsAsyncClient.get_tool", "method": { - "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes.UpdateSessionEntityType", + "fullName": "google.cloud.dialogflow.v2.Tools.GetTool", "service": { - "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes", - "shortName": "SessionEntityTypes" + "fullName": "google.cloud.dialogflow.v2.Tools", + "shortName": "Tools" }, - "shortName": "UpdateSessionEntityType" + "shortName": "GetTool" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.UpdateSessionEntityTypeRequest" - }, - { - "name": "session_entity_type", - "type": "google.cloud.dialogflow_v2.types.SessionEntityType" + "type": "google.cloud.dialogflow_v2.types.GetToolRequest" }, { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "name", + "type": "str" }, { "name": "retry", @@ -17630,22 +19910,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.types.SessionEntityType", - "shortName": "update_session_entity_type" + "resultType": "google.cloud.dialogflow_v2.types.Tool", + "shortName": "get_tool" }, - "description": "Sample for UpdateSessionEntityType", - "file": "dialogflow_v2_generated_session_entity_types_update_session_entity_type_async.py", + "description": "Sample for GetTool", + "file": "dialogflow_v2_generated_tools_get_tool_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_SessionEntityTypes_UpdateSessionEntityType_async", + "regionTag": "dialogflow_v2_generated_Tools_GetTool_async", "segments": [ { - "end": 57, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 57, + "end": 51, "start": 27, "type": "SHORT" }, @@ -17655,51 +19935,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 51, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 54, - "start": 52, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 58, - "start": 55, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_session_entity_types_update_session_entity_type_async.py" + "title": "dialogflow_v2_generated_tools_get_tool_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesClient", - "shortName": "SessionEntityTypesClient" + "fullName": "google.cloud.dialogflow_v2.ToolsClient", + "shortName": "ToolsClient" }, - "fullName": "google.cloud.dialogflow_v2.SessionEntityTypesClient.update_session_entity_type", + "fullName": "google.cloud.dialogflow_v2.ToolsClient.get_tool", "method": { - "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes.UpdateSessionEntityType", + "fullName": "google.cloud.dialogflow.v2.Tools.GetTool", "service": { - "fullName": "google.cloud.dialogflow.v2.SessionEntityTypes", - "shortName": "SessionEntityTypes" + "fullName": "google.cloud.dialogflow.v2.Tools", + "shortName": "Tools" }, - "shortName": "UpdateSessionEntityType" + "shortName": "GetTool" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.UpdateSessionEntityTypeRequest" + "type": "google.cloud.dialogflow_v2.types.GetToolRequest" }, { - "name": "session_entity_type", - "type": "google.cloud.dialogflow_v2.types.SessionEntityType" - }, - { - "name": "update_mask", - "type": "google.protobuf.field_mask_pb2.FieldMask" + "name": "name", + "type": "str" }, { "name": "retry", @@ -17714,22 +19990,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.types.SessionEntityType", - "shortName": "update_session_entity_type" + "resultType": "google.cloud.dialogflow_v2.types.Tool", + "shortName": "get_tool" }, - "description": "Sample for UpdateSessionEntityType", - "file": "dialogflow_v2_generated_session_entity_types_update_session_entity_type_sync.py", + "description": "Sample for GetTool", + "file": "dialogflow_v2_generated_tools_get_tool_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_SessionEntityTypes_UpdateSessionEntityType_sync", + "regionTag": "dialogflow_v2_generated_Tools_GetTool_sync", "segments": [ { - "end": 57, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 57, + "end": 51, "start": 27, "type": "SHORT" }, @@ -17739,53 +20015,49 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 51, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 54, - "start": 52, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 58, - "start": 55, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_session_entity_types_update_session_entity_type_sync.py" + "title": "dialogflow_v2_generated_tools_get_tool_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflow_v2.SessionsAsyncClient", - "shortName": "SessionsAsyncClient" + "fullName": "google.cloud.dialogflow_v2.ToolsAsyncClient", + "shortName": "ToolsAsyncClient" }, - "fullName": "google.cloud.dialogflow_v2.SessionsAsyncClient.detect_intent", + "fullName": "google.cloud.dialogflow_v2.ToolsAsyncClient.list_tools", "method": { - "fullName": "google.cloud.dialogflow.v2.Sessions.DetectIntent", + "fullName": "google.cloud.dialogflow.v2.Tools.ListTools", "service": { - "fullName": "google.cloud.dialogflow.v2.Sessions", - "shortName": "Sessions" + "fullName": "google.cloud.dialogflow.v2.Tools", + "shortName": "Tools" }, - "shortName": "DetectIntent" + "shortName": "ListTools" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.DetectIntentRequest" + "type": "google.cloud.dialogflow_v2.types.ListToolsRequest" }, { - "name": "session", + "name": "parent", "type": "str" }, - { - "name": "query_input", - "type": "google.cloud.dialogflow_v2.types.QueryInput" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -17799,22 +20071,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.types.DetectIntentResponse", - "shortName": "detect_intent" + "resultType": "google.cloud.dialogflow_v2.services.tools.pagers.ListToolsAsyncPager", + "shortName": "list_tools" }, - "description": "Sample for DetectIntent", - "file": "dialogflow_v2_generated_sessions_detect_intent_async.py", + "description": "Sample for ListTools", + "file": "dialogflow_v2_generated_tools_list_tools_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Sessions_DetectIntent_async", + "regionTag": "dialogflow_v2_generated_Tools_ListTools_async", "segments": [ { - "end": 57, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 57, + "end": 52, "start": 27, "type": "SHORT" }, @@ -17824,52 +20096,48 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 51, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 54, - "start": 52, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 58, - "start": 55, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_sessions_detect_intent_async.py" + "title": "dialogflow_v2_generated_tools_list_tools_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflow_v2.SessionsClient", - "shortName": "SessionsClient" + "fullName": "google.cloud.dialogflow_v2.ToolsClient", + "shortName": "ToolsClient" }, - "fullName": "google.cloud.dialogflow_v2.SessionsClient.detect_intent", + "fullName": "google.cloud.dialogflow_v2.ToolsClient.list_tools", "method": { - "fullName": "google.cloud.dialogflow.v2.Sessions.DetectIntent", + "fullName": "google.cloud.dialogflow.v2.Tools.ListTools", "service": { - "fullName": "google.cloud.dialogflow.v2.Sessions", - "shortName": "Sessions" + "fullName": "google.cloud.dialogflow.v2.Tools", + "shortName": "Tools" }, - "shortName": "DetectIntent" + "shortName": "ListTools" }, "parameters": [ { "name": "request", - "type": "google.cloud.dialogflow_v2.types.DetectIntentRequest" + "type": "google.cloud.dialogflow_v2.types.ListToolsRequest" }, { - "name": "session", + "name": "parent", "type": "str" }, - { - "name": "query_input", - "type": "google.cloud.dialogflow_v2.types.QueryInput" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -17883,22 +20151,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.dialogflow_v2.types.DetectIntentResponse", - "shortName": "detect_intent" + "resultType": "google.cloud.dialogflow_v2.services.tools.pagers.ListToolsPager", + "shortName": "list_tools" }, - "description": "Sample for DetectIntent", - "file": "dialogflow_v2_generated_sessions_detect_intent_sync.py", + "description": "Sample for ListTools", + "file": "dialogflow_v2_generated_tools_list_tools_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Sessions_DetectIntent_sync", + "regionTag": "dialogflow_v2_generated_Tools_ListTools_sync", "segments": [ { - "end": 57, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 57, + "end": 52, "start": 27, "type": "SHORT" }, @@ -17908,44 +20176,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 51, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 54, - "start": 52, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 58, - "start": 55, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_sessions_detect_intent_sync.py" + "title": "dialogflow_v2_generated_tools_list_tools_sync.py" }, { "canonical": true, "clientMethod": { "async": true, "client": { - "fullName": "google.cloud.dialogflow_v2.SessionsAsyncClient", - "shortName": "SessionsAsyncClient" + "fullName": "google.cloud.dialogflow_v2.ToolsAsyncClient", + "shortName": "ToolsAsyncClient" }, - "fullName": "google.cloud.dialogflow_v2.SessionsAsyncClient.streaming_detect_intent", + "fullName": "google.cloud.dialogflow_v2.ToolsAsyncClient.update_tool", "method": { - "fullName": "google.cloud.dialogflow.v2.Sessions.StreamingDetectIntent", + "fullName": "google.cloud.dialogflow.v2.Tools.UpdateTool", "service": { - "fullName": "google.cloud.dialogflow.v2.Sessions", - "shortName": "Sessions" + "fullName": "google.cloud.dialogflow.v2.Tools", + "shortName": "Tools" }, - "shortName": "StreamingDetectIntent" + "shortName": "UpdateTool" }, "parameters": [ { - "name": "requests", - "type": "Iterator[google.cloud.dialogflow_v2.types.StreamingDetectIntentRequest]" + "name": "request", + "type": "google.cloud.dialogflow_v2.types.UpdateToolRequest" + }, + { + "name": "tool", + "type": "google.cloud.dialogflow_v2.types.Tool" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -17960,22 +20236,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "Iterable[google.cloud.dialogflow_v2.types.StreamingDetectIntentResponse]", - "shortName": "streaming_detect_intent" + "resultType": "google.cloud.dialogflow_v2.types.Tool", + "shortName": "update_tool" }, - "description": "Sample for StreamingDetectIntent", - "file": "dialogflow_v2_generated_sessions_streaming_detect_intent_async.py", + "description": "Sample for UpdateTool", + "file": "dialogflow_v2_generated_tools_update_tool_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Sessions_StreamingDetectIntent_async", + "regionTag": "dialogflow_v2_generated_Tools_UpdateTool_async", "segments": [ { - "end": 68, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 68, + "end": 55, "start": 27, "type": "SHORT" }, @@ -17985,43 +20261,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 61, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 64, - "start": 62, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 69, - "start": 65, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_sessions_streaming_detect_intent_async.py" + "title": "dialogflow_v2_generated_tools_update_tool_async.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.dialogflow_v2.SessionsClient", - "shortName": "SessionsClient" + "fullName": "google.cloud.dialogflow_v2.ToolsClient", + "shortName": "ToolsClient" }, - "fullName": "google.cloud.dialogflow_v2.SessionsClient.streaming_detect_intent", + "fullName": "google.cloud.dialogflow_v2.ToolsClient.update_tool", "method": { - "fullName": "google.cloud.dialogflow.v2.Sessions.StreamingDetectIntent", + "fullName": "google.cloud.dialogflow.v2.Tools.UpdateTool", "service": { - "fullName": "google.cloud.dialogflow.v2.Sessions", - "shortName": "Sessions" + "fullName": "google.cloud.dialogflow.v2.Tools", + "shortName": "Tools" }, - "shortName": "StreamingDetectIntent" + "shortName": "UpdateTool" }, "parameters": [ { - "name": "requests", - "type": "Iterator[google.cloud.dialogflow_v2.types.StreamingDetectIntentRequest]" + "name": "request", + "type": "google.cloud.dialogflow_v2.types.UpdateToolRequest" + }, + { + "name": "tool", + "type": "google.cloud.dialogflow_v2.types.Tool" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -18036,22 +20320,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "Iterable[google.cloud.dialogflow_v2.types.StreamingDetectIntentResponse]", - "shortName": "streaming_detect_intent" + "resultType": "google.cloud.dialogflow_v2.types.Tool", + "shortName": "update_tool" }, - "description": "Sample for StreamingDetectIntent", - "file": "dialogflow_v2_generated_sessions_streaming_detect_intent_sync.py", + "description": "Sample for UpdateTool", + "file": "dialogflow_v2_generated_tools_update_tool_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "dialogflow_v2_generated_Sessions_StreamingDetectIntent_sync", + "regionTag": "dialogflow_v2_generated_Tools_UpdateTool_sync", "segments": [ { - "end": 68, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 68, + "end": 55, "start": 27, "type": "SHORT" }, @@ -18061,22 +20345,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 61, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 64, - "start": 62, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 69, - "start": 65, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "dialogflow_v2_generated_sessions_streaming_detect_intent_sync.py" + "title": "dialogflow_v2_generated_tools_update_tool_sync.py" }, { "canonical": true, diff --git a/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2/test_answer_records.py b/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2/test_answer_records.py index 8b20692594a8..39c9615202f5 100644 --- a/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2/test_answer_records.py +++ b/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2/test_answer_records.py @@ -63,7 +63,15 @@ pagers, transports, ) -from google.cloud.dialogflow_v2.types import context, intent, participant, session +from google.cloud.dialogflow_v2.types import ( + context, + generator, + intent, + participant, + session, + tool_call, +) +from google.cloud.dialogflow_v2.types import agent_coaching_instruction from google.cloud.dialogflow_v2.types import answer_record from google.cloud.dialogflow_v2.types import answer_record as gcd_answer_record @@ -3318,6 +3326,81 @@ def test_update_answer_record_rest_call_success(request_type): }, "answer_record": "answer_record_value", }, + "generator_suggestion": { + "free_form_suggestion": {"response": "response_value"}, + "summary_suggestion": { + "summary_sections": [ + {"section": "section_value", "summary": "summary_value"} + ] + }, + "agent_coaching_suggestion": { + "applicable_instructions": [ + { + "display_name": "display_name_value", + "display_details": "display_details_value", + "condition": "condition_value", + "agent_action": "agent_action_value", + "system_action": "system_action_value", + "duplicate_check_result": { + "duplicate_suggestions": [ + { + "answer_record": "answer_record_value", + "suggestion_index": 1727, + "similarity_score": 0.17300000000000001, + } + ] + }, + "triggering_event": 1, + } + ], + "agent_action_suggestions": [ + { + "agent_action": "agent_action_value", + "sources": {"instruction_indexes": [2066, 2067]}, + "duplicate_check_result": { + "duplicate_suggestions": [ + { + "answer_record": "answer_record_value", + "sources": {}, + "suggestion_index": 1727, + "similarity_score": 0.17300000000000001, + } + ] + }, + } + ], + "sample_responses": [ + { + "response_text": "response_text_value", + "sources": {}, + "duplicate_check_result": {}, + } + ], + }, + "tool_call_info": [ + { + "tool_call": { + "tool": "tool_value", + "tool_display_name": "tool_display_name_value", + "tool_display_details": "tool_display_details_value", + "action": "action_value", + "input_parameters": {}, + "create_time": {}, + "answer_record": "answer_record_value", + "state": 1, + }, + "tool_call_result": { + "tool": "tool_value", + "action": "action_value", + "error": {"message": "message_value"}, + "raw_content": b"raw_content_blob", + "content": "content_value", + "create_time": {}, + "answer_record": "answer_record_value", + }, + } + ], + }, }, } # The version of a generated dependency at test runtime may differ from the version used during generation. @@ -4350,8 +4433,34 @@ def test_parse_intent_path(): assert expected == actual +def test_tool_path(): + project = "whelk" + location = "octopus" + tool = "oyster" + expected = "projects/{project}/locations/{location}/tools/{tool}".format( + project=project, + location=location, + tool=tool, + ) + actual = AnswerRecordsClient.tool_path(project, location, tool) + assert expected == actual + + +def test_parse_tool_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "tool": "mussel", + } + path = AnswerRecordsClient.tool_path(**expected) + + # Check that the path construction is reversible. + actual = AnswerRecordsClient.parse_tool_path(path) + assert expected == actual + + def test_common_billing_account_path(): - billing_account = "whelk" + billing_account = "winkle" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -4361,7 +4470,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "octopus", + "billing_account": "nautilus", } path = AnswerRecordsClient.common_billing_account_path(**expected) @@ -4371,7 +4480,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "oyster" + folder = "scallop" expected = "folders/{folder}".format( folder=folder, ) @@ -4381,7 +4490,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "nudibranch", + "folder": "abalone", } path = AnswerRecordsClient.common_folder_path(**expected) @@ -4391,7 +4500,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "cuttlefish" + organization = "squid" expected = "organizations/{organization}".format( organization=organization, ) @@ -4401,7 +4510,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "mussel", + "organization": "clam", } path = AnswerRecordsClient.common_organization_path(**expected) @@ -4411,7 +4520,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "winkle" + project = "whelk" expected = "projects/{project}".format( project=project, ) @@ -4421,7 +4530,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "nautilus", + "project": "octopus", } path = AnswerRecordsClient.common_project_path(**expected) @@ -4431,8 +4540,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "scallop" - location = "abalone" + project = "oyster" + location = "nudibranch" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -4443,8 +4552,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "squid", - "location": "clam", + "project": "cuttlefish", + "location": "mussel", } path = AnswerRecordsClient.common_location_path(**expected) diff --git a/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2/test_conversation_profiles.py b/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2/test_conversation_profiles.py index 17a886537047..bb9ae56f368b 100644 --- a/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2/test_conversation_profiles.py +++ b/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2/test_conversation_profiles.py @@ -77,7 +77,7 @@ ) from google.cloud.dialogflow_v2.types import audio_config from google.cloud.dialogflow_v2.types import conversation_profile -from google.cloud.dialogflow_v2.types import participant +from google.cloud.dialogflow_v2.types import generator, participant CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -6400,6 +6400,12 @@ def test_create_conversation_profile_rest_call_success(request_type): "enable_query_suggestion_when_no_answer": True, "enable_conversation_augmented_query": True, "enable_query_suggestion_only": True, + "enable_response_debug_info": True, + "rai_settings": { + "rai_category_configs": [ + {"category": 1, "sensitivity_level": 1} + ] + }, "suggestion_trigger_settings": { "no_smalltalk": True, "only_end_user": True, @@ -6438,6 +6444,9 @@ def test_create_conversation_profile_rest_call_success(request_type): "group_suggestion_responses": True, "generators": ["generators_value1", "generators_value2"], "disable_high_latency_features_sync_delivery": True, + "skip_empty_event_based_suggestion": True, + "use_unredacted_conversation_data": True, + "enable_async_tool_call": True, }, "end_user_suggestion_config": {}, "message_analysis_config": { @@ -6480,6 +6489,13 @@ def test_create_conversation_profile_rest_call_success(request_type): "effects_profile_id_value2", ], "voice": {"name": "name_value", "ssml_gender": 1}, + "pronunciations": [ + { + "phrase": "phrase_value", + "phonetic_encoding": 1, + "pronunciation": "pronunciation_value", + } + ], }, } # The version of a generated dependency at test runtime may differ from the version used during generation. @@ -6724,6 +6740,12 @@ def test_update_conversation_profile_rest_call_success(request_type): "enable_query_suggestion_when_no_answer": True, "enable_conversation_augmented_query": True, "enable_query_suggestion_only": True, + "enable_response_debug_info": True, + "rai_settings": { + "rai_category_configs": [ + {"category": 1, "sensitivity_level": 1} + ] + }, "suggestion_trigger_settings": { "no_smalltalk": True, "only_end_user": True, @@ -6762,6 +6784,9 @@ def test_update_conversation_profile_rest_call_success(request_type): "group_suggestion_responses": True, "generators": ["generators_value1", "generators_value2"], "disable_high_latency_features_sync_delivery": True, + "skip_empty_event_based_suggestion": True, + "use_unredacted_conversation_data": True, + "enable_async_tool_call": True, }, "end_user_suggestion_config": {}, "message_analysis_config": { @@ -6804,6 +6829,13 @@ def test_update_conversation_profile_rest_call_success(request_type): "effects_profile_id_value2", ], "voice": {"name": "name_value", "ssml_gender": 1}, + "pronunciations": [ + { + "phrase": "phrase_value", + "phonetic_encoding": 1, + "pronunciation": "pronunciation_value", + } + ], }, } # The version of a generated dependency at test runtime may differ from the version used during generation. diff --git a/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2/test_conversations.py b/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2/test_conversations.py index a4ebfadf5fe3..0ac20c608523 100644 --- a/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2/test_conversations.py +++ b/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2/test_conversations.py @@ -63,13 +63,14 @@ pagers, transports, ) +from google.cloud.dialogflow_v2.types import agent_coaching_instruction, audio_config from google.cloud.dialogflow_v2.types import ( conversation_profile, generator, participant, session, + tool_call, ) -from google.cloud.dialogflow_v2.types import audio_config from google.cloud.dialogflow_v2.types import conversation from google.cloud.dialogflow_v2.types import conversation as gcd_conversation @@ -4530,6 +4531,7 @@ def test_generate_stateless_suggestion_non_empty_request_with_auto_populated_fie request = conversation.GenerateStatelessSuggestionRequest( parent="parent_value", generator_name="generator_name_value", + security_settings="security_settings_value", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4545,6 +4547,7 @@ def test_generate_stateless_suggestion_non_empty_request_with_auto_populated_fie assert args[0] == conversation.GenerateStatelessSuggestionRequest( parent="parent_value", generator_name="generator_name_value", + security_settings="security_settings_value", ) @@ -10977,8 +10980,34 @@ def test_parse_phrase_set_path(): assert expected == actual +def test_tool_path(): + project = "whelk" + location = "octopus" + tool = "oyster" + expected = "projects/{project}/locations/{location}/tools/{tool}".format( + project=project, + location=location, + tool=tool, + ) + actual = ConversationsClient.tool_path(project, location, tool) + assert expected == actual + + +def test_parse_tool_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "tool": "mussel", + } + path = ConversationsClient.tool_path(**expected) + + # Check that the path construction is reversible. + actual = ConversationsClient.parse_tool_path(path) + assert expected == actual + + def test_common_billing_account_path(): - billing_account = "whelk" + billing_account = "winkle" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -10988,7 +11017,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "octopus", + "billing_account": "nautilus", } path = ConversationsClient.common_billing_account_path(**expected) @@ -10998,7 +11027,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "oyster" + folder = "scallop" expected = "folders/{folder}".format( folder=folder, ) @@ -11008,7 +11037,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "nudibranch", + "folder": "abalone", } path = ConversationsClient.common_folder_path(**expected) @@ -11018,7 +11047,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "cuttlefish" + organization = "squid" expected = "organizations/{organization}".format( organization=organization, ) @@ -11028,7 +11057,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "mussel", + "organization": "clam", } path = ConversationsClient.common_organization_path(**expected) @@ -11038,7 +11067,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "winkle" + project = "whelk" expected = "projects/{project}".format( project=project, ) @@ -11048,7 +11077,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "nautilus", + "project": "octopus", } path = ConversationsClient.common_project_path(**expected) @@ -11058,8 +11087,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "scallop" - location = "abalone" + project = "oyster" + location = "nudibranch" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -11070,8 +11099,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "squid", - "location": "clam", + "project": "cuttlefish", + "location": "mussel", } path = ConversationsClient.common_location_path(**expected) diff --git a/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2/test_generator_evaluations.py b/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2/test_generator_evaluations.py new file mode 100644 index 000000000000..47d9d4fa0a60 --- /dev/null +++ b/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2/test_generator_evaluations.py @@ -0,0 +1,6912 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +from collections.abc import AsyncIterable, Iterable +import json +import math + +from google.api_core import api_core_version +from google.protobuf import json_format +import grpc +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest +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 + +from google.api_core import ( + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + operation, + operations_v1, + path_template, +) +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import operation_async # type: ignore +from google.api_core import retry as retries +import google.auth +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.protobuf import any_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore + +from google.cloud.dialogflow_v2.services.generator_evaluations import ( + GeneratorEvaluationsAsyncClient, + GeneratorEvaluationsClient, + pagers, + transports, +) +from google.cloud.dialogflow_v2.types import agent_coaching_instruction, generator +from google.cloud.dialogflow_v2.types import ( + generator_evaluation as gcd_generator_evaluation, +) +from google.cloud.dialogflow_v2.types import generator_evaluation +from google.cloud.dialogflow_v2.types import operations, tool_call + +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 GeneratorEvaluationsClient._get_default_mtls_endpoint(None) is None + assert ( + GeneratorEvaluationsClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + GeneratorEvaluationsClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + GeneratorEvaluationsClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + GeneratorEvaluationsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + GeneratorEvaluationsClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + + +def test__read_environment_variables(): + assert GeneratorEvaluationsClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert GeneratorEvaluationsClient._read_environment_variables() == ( + True, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert GeneratorEvaluationsClient._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: + GeneratorEvaluationsClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + else: + assert GeneratorEvaluationsClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert GeneratorEvaluationsClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert GeneratorEvaluationsClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert GeneratorEvaluationsClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + GeneratorEvaluationsClient._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 GeneratorEvaluationsClient._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 GeneratorEvaluationsClient._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 GeneratorEvaluationsClient._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 GeneratorEvaluationsClient._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 GeneratorEvaluationsClient._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 GeneratorEvaluationsClient._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 GeneratorEvaluationsClient._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 GeneratorEvaluationsClient._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 GeneratorEvaluationsClient._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 GeneratorEvaluationsClient._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): + GeneratorEvaluationsClient._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 GeneratorEvaluationsClient._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 GeneratorEvaluationsClient._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 GeneratorEvaluationsClient._get_client_cert_source(None, False) is None + assert ( + GeneratorEvaluationsClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + GeneratorEvaluationsClient._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 ( + GeneratorEvaluationsClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + GeneratorEvaluationsClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + GeneratorEvaluationsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(GeneratorEvaluationsClient), +) +@mock.patch.object( + GeneratorEvaluationsAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(GeneratorEvaluationsAsyncClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = GeneratorEvaluationsClient._DEFAULT_UNIVERSE + default_endpoint = GeneratorEvaluationsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = GeneratorEvaluationsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + GeneratorEvaluationsClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + GeneratorEvaluationsClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == GeneratorEvaluationsClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + GeneratorEvaluationsClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + GeneratorEvaluationsClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == GeneratorEvaluationsClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + GeneratorEvaluationsClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == GeneratorEvaluationsClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + GeneratorEvaluationsClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + GeneratorEvaluationsClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + GeneratorEvaluationsClient._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 ( + GeneratorEvaluationsClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + GeneratorEvaluationsClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + GeneratorEvaluationsClient._get_universe_domain(None, None) + == GeneratorEvaluationsClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + GeneratorEvaluationsClient._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 = GeneratorEvaluationsClient(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 = GeneratorEvaluationsClient(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", + [ + (GeneratorEvaluationsClient, "grpc"), + (GeneratorEvaluationsAsyncClient, "grpc_asyncio"), + (GeneratorEvaluationsClient, "rest"), + ], +) +def test_generator_evaluations_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 == ( + "dialogflow.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://dialogflow.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.GeneratorEvaluationsGrpcTransport, "grpc"), + (transports.GeneratorEvaluationsGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.GeneratorEvaluationsRestTransport, "rest"), + ], +) +def test_generator_evaluations_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", + [ + (GeneratorEvaluationsClient, "grpc"), + (GeneratorEvaluationsAsyncClient, "grpc_asyncio"), + (GeneratorEvaluationsClient, "rest"), + ], +) +def test_generator_evaluations_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 == ( + "dialogflow.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://dialogflow.googleapis.com" + ) + + +def test_generator_evaluations_client_get_transport_class(): + transport = GeneratorEvaluationsClient.get_transport_class() + available_transports = [ + transports.GeneratorEvaluationsGrpcTransport, + transports.GeneratorEvaluationsRestTransport, + ] + assert transport in available_transports + + transport = GeneratorEvaluationsClient.get_transport_class("grpc") + assert transport == transports.GeneratorEvaluationsGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + GeneratorEvaluationsClient, + transports.GeneratorEvaluationsGrpcTransport, + "grpc", + ), + ( + GeneratorEvaluationsAsyncClient, + transports.GeneratorEvaluationsGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + GeneratorEvaluationsClient, + transports.GeneratorEvaluationsRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + GeneratorEvaluationsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(GeneratorEvaluationsClient), +) +@mock.patch.object( + GeneratorEvaluationsAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(GeneratorEvaluationsAsyncClient), +) +def test_generator_evaluations_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(GeneratorEvaluationsClient, "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(GeneratorEvaluationsClient, "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", + [ + ( + GeneratorEvaluationsClient, + transports.GeneratorEvaluationsGrpcTransport, + "grpc", + "true", + ), + ( + GeneratorEvaluationsAsyncClient, + transports.GeneratorEvaluationsGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + GeneratorEvaluationsClient, + transports.GeneratorEvaluationsGrpcTransport, + "grpc", + "false", + ), + ( + GeneratorEvaluationsAsyncClient, + transports.GeneratorEvaluationsGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + GeneratorEvaluationsClient, + transports.GeneratorEvaluationsRestTransport, + "rest", + "true", + ), + ( + GeneratorEvaluationsClient, + transports.GeneratorEvaluationsRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + GeneratorEvaluationsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(GeneratorEvaluationsClient), +) +@mock.patch.object( + GeneratorEvaluationsAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(GeneratorEvaluationsAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_generator_evaluations_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", [GeneratorEvaluationsClient, GeneratorEvaluationsAsyncClient] +) +@mock.patch.object( + GeneratorEvaluationsClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(GeneratorEvaluationsClient), +) +@mock.patch.object( + GeneratorEvaluationsAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(GeneratorEvaluationsAsyncClient), +) +def test_generator_evaluations_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", [GeneratorEvaluationsClient, GeneratorEvaluationsAsyncClient] +) +@mock.patch.object( + GeneratorEvaluationsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(GeneratorEvaluationsClient), +) +@mock.patch.object( + GeneratorEvaluationsAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(GeneratorEvaluationsAsyncClient), +) +def test_generator_evaluations_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = GeneratorEvaluationsClient._DEFAULT_UNIVERSE + default_endpoint = GeneratorEvaluationsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = GeneratorEvaluationsClient._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", + [ + ( + GeneratorEvaluationsClient, + transports.GeneratorEvaluationsGrpcTransport, + "grpc", + ), + ( + GeneratorEvaluationsAsyncClient, + transports.GeneratorEvaluationsGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ( + GeneratorEvaluationsClient, + transports.GeneratorEvaluationsRestTransport, + "rest", + ), + ], +) +def test_generator_evaluations_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", + [ + ( + GeneratorEvaluationsClient, + transports.GeneratorEvaluationsGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + GeneratorEvaluationsAsyncClient, + transports.GeneratorEvaluationsGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + GeneratorEvaluationsClient, + transports.GeneratorEvaluationsRestTransport, + "rest", + None, + ), + ], +) +def test_generator_evaluations_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_generator_evaluations_client_client_options_from_dict(): + with mock.patch( + "google.cloud.dialogflow_v2.services.generator_evaluations.transports.GeneratorEvaluationsGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = GeneratorEvaluationsClient( + 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", + [ + ( + GeneratorEvaluationsClient, + transports.GeneratorEvaluationsGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + GeneratorEvaluationsAsyncClient, + transports.GeneratorEvaluationsGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_generator_evaluations_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( + "dialogflow.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + scopes=None, + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gcd_generator_evaluation.CreateGeneratorEvaluationRequest, + dict, + ], +) +def test_create_generator_evaluation(request_type, transport: str = "grpc"): + client = GeneratorEvaluationsClient( + 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_generator_evaluation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_generator_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcd_generator_evaluation.CreateGeneratorEvaluationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_generator_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 = GeneratorEvaluationsClient( + 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 = gcd_generator_evaluation.CreateGeneratorEvaluationRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_generator_evaluation), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_generator_evaluation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_generator_evaluation.CreateGeneratorEvaluationRequest( + parent="parent_value", + ) + + +def test_create_generator_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 = GeneratorEvaluationsClient( + 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_generator_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_generator_evaluation + ] = mock_rpc + request = {} + client.create_generator_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.create_generator_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_generator_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 = GeneratorEvaluationsAsyncClient( + 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_generator_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_generator_evaluation + ] = mock_rpc + + request = {} + await client.create_generator_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.create_generator_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_generator_evaluation_async( + transport: str = "grpc_asyncio", + request_type=gcd_generator_evaluation.CreateGeneratorEvaluationRequest, +): + client = GeneratorEvaluationsAsyncClient( + 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_generator_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.create_generator_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcd_generator_evaluation.CreateGeneratorEvaluationRequest() + 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_generator_evaluation_async_from_dict(): + await test_create_generator_evaluation_async(request_type=dict) + + +def test_create_generator_evaluation_field_headers(): + client = GeneratorEvaluationsClient( + 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 = gcd_generator_evaluation.CreateGeneratorEvaluationRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_generator_evaluation), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_generator_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_generator_evaluation_field_headers_async(): + client = GeneratorEvaluationsAsyncClient( + 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 = gcd_generator_evaluation.CreateGeneratorEvaluationRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_generator_evaluation), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_generator_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_generator_evaluation_flattened(): + client = GeneratorEvaluationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_generator_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.create_generator_evaluation( + parent="parent_value", + generator_evaluation=gcd_generator_evaluation.GeneratorEvaluation( + 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].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].generator_evaluation + mock_val = gcd_generator_evaluation.GeneratorEvaluation(name="name_value") + assert arg == mock_val + + +def test_create_generator_evaluation_flattened_error(): + client = GeneratorEvaluationsClient( + 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_generator_evaluation( + gcd_generator_evaluation.CreateGeneratorEvaluationRequest(), + parent="parent_value", + generator_evaluation=gcd_generator_evaluation.GeneratorEvaluation( + name="name_value" + ), + ) + + +@pytest.mark.asyncio +async def test_create_generator_evaluation_flattened_async(): + client = GeneratorEvaluationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_generator_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.create_generator_evaluation( + parent="parent_value", + generator_evaluation=gcd_generator_evaluation.GeneratorEvaluation( + 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].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].generator_evaluation + mock_val = gcd_generator_evaluation.GeneratorEvaluation(name="name_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_generator_evaluation_flattened_error_async(): + client = GeneratorEvaluationsAsyncClient( + 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_generator_evaluation( + gcd_generator_evaluation.CreateGeneratorEvaluationRequest(), + parent="parent_value", + generator_evaluation=gcd_generator_evaluation.GeneratorEvaluation( + name="name_value" + ), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + generator_evaluation.GetGeneratorEvaluationRequest, + dict, + ], +) +def test_get_generator_evaluation(request_type, transport: str = "grpc"): + client = GeneratorEvaluationsClient( + 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_generator_evaluation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = generator_evaluation.GeneratorEvaluation( + name="name_value", + display_name="display_name_value", + satisfies_pzs=True, + satisfies_pzi=True, + ) + response = client.get_generator_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = generator_evaluation.GetGeneratorEvaluationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, generator_evaluation.GeneratorEvaluation) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True + + +def test_get_generator_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 = GeneratorEvaluationsClient( + 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 = generator_evaluation.GetGeneratorEvaluationRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_generator_evaluation), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_generator_evaluation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == generator_evaluation.GetGeneratorEvaluationRequest( + name="name_value", + ) + + +def test_get_generator_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 = GeneratorEvaluationsClient( + 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_generator_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_generator_evaluation + ] = mock_rpc + request = {} + client.get_generator_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_generator_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_generator_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 = GeneratorEvaluationsAsyncClient( + 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_generator_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_generator_evaluation + ] = mock_rpc + + request = {} + await client.get_generator_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_generator_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_generator_evaluation_async( + transport: str = "grpc_asyncio", + request_type=generator_evaluation.GetGeneratorEvaluationRequest, +): + client = GeneratorEvaluationsAsyncClient( + 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_generator_evaluation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + generator_evaluation.GeneratorEvaluation( + name="name_value", + display_name="display_name_value", + satisfies_pzs=True, + satisfies_pzi=True, + ) + ) + response = await client.get_generator_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = generator_evaluation.GetGeneratorEvaluationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, generator_evaluation.GeneratorEvaluation) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True + + +@pytest.mark.asyncio +async def test_get_generator_evaluation_async_from_dict(): + await test_get_generator_evaluation_async(request_type=dict) + + +def test_get_generator_evaluation_field_headers(): + client = GeneratorEvaluationsClient( + 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 = generator_evaluation.GetGeneratorEvaluationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_generator_evaluation), "__call__" + ) as call: + call.return_value = generator_evaluation.GeneratorEvaluation() + client.get_generator_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_generator_evaluation_field_headers_async(): + client = GeneratorEvaluationsAsyncClient( + 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 = generator_evaluation.GetGeneratorEvaluationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_generator_evaluation), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + generator_evaluation.GeneratorEvaluation() + ) + await client.get_generator_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_generator_evaluation_flattened(): + client = GeneratorEvaluationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_generator_evaluation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = generator_evaluation.GeneratorEvaluation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_generator_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_generator_evaluation_flattened_error(): + client = GeneratorEvaluationsClient( + 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_generator_evaluation( + generator_evaluation.GetGeneratorEvaluationRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_generator_evaluation_flattened_async(): + client = GeneratorEvaluationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_generator_evaluation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = generator_evaluation.GeneratorEvaluation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + generator_evaluation.GeneratorEvaluation() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_generator_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_generator_evaluation_flattened_error_async(): + client = GeneratorEvaluationsAsyncClient( + 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_generator_evaluation( + generator_evaluation.GetGeneratorEvaluationRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + generator_evaluation.ListGeneratorEvaluationsRequest, + dict, + ], +) +def test_list_generator_evaluations(request_type, transport: str = "grpc"): + client = GeneratorEvaluationsClient( + 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_generator_evaluations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = generator_evaluation.ListGeneratorEvaluationsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_generator_evaluations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = generator_evaluation.ListGeneratorEvaluationsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListGeneratorEvaluationsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_generator_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 = GeneratorEvaluationsClient( + 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 = generator_evaluation.ListGeneratorEvaluationsRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_generator_evaluations), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_generator_evaluations(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == generator_evaluation.ListGeneratorEvaluationsRequest( + parent="parent_value", + page_token="page_token_value", + ) + + +def test_list_generator_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 = GeneratorEvaluationsClient( + 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_generator_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_generator_evaluations + ] = mock_rpc + request = {} + client.list_generator_evaluations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_generator_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_generator_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 = GeneratorEvaluationsAsyncClient( + 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_generator_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_generator_evaluations + ] = mock_rpc + + request = {} + await client.list_generator_evaluations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_generator_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_generator_evaluations_async( + transport: str = "grpc_asyncio", + request_type=generator_evaluation.ListGeneratorEvaluationsRequest, +): + client = GeneratorEvaluationsAsyncClient( + 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_generator_evaluations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + generator_evaluation.ListGeneratorEvaluationsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_generator_evaluations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = generator_evaluation.ListGeneratorEvaluationsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListGeneratorEvaluationsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_generator_evaluations_async_from_dict(): + await test_list_generator_evaluations_async(request_type=dict) + + +def test_list_generator_evaluations_field_headers(): + client = GeneratorEvaluationsClient( + 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 = generator_evaluation.ListGeneratorEvaluationsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_generator_evaluations), "__call__" + ) as call: + call.return_value = generator_evaluation.ListGeneratorEvaluationsResponse() + client.list_generator_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_generator_evaluations_field_headers_async(): + client = GeneratorEvaluationsAsyncClient( + 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 = generator_evaluation.ListGeneratorEvaluationsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_generator_evaluations), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + generator_evaluation.ListGeneratorEvaluationsResponse() + ) + await client.list_generator_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_generator_evaluations_flattened(): + client = GeneratorEvaluationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_generator_evaluations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = generator_evaluation.ListGeneratorEvaluationsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_generator_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_generator_evaluations_flattened_error(): + client = GeneratorEvaluationsClient( + 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_generator_evaluations( + generator_evaluation.ListGeneratorEvaluationsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_generator_evaluations_flattened_async(): + client = GeneratorEvaluationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_generator_evaluations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = generator_evaluation.ListGeneratorEvaluationsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + generator_evaluation.ListGeneratorEvaluationsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_generator_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_generator_evaluations_flattened_error_async(): + client = GeneratorEvaluationsAsyncClient( + 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_generator_evaluations( + generator_evaluation.ListGeneratorEvaluationsRequest(), + parent="parent_value", + ) + + +def test_list_generator_evaluations_pager(transport_name: str = "grpc"): + client = GeneratorEvaluationsClient( + 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_generator_evaluations), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + generator_evaluation.ListGeneratorEvaluationsResponse( + generator_evaluations=[ + generator_evaluation.GeneratorEvaluation(), + generator_evaluation.GeneratorEvaluation(), + generator_evaluation.GeneratorEvaluation(), + ], + next_page_token="abc", + ), + generator_evaluation.ListGeneratorEvaluationsResponse( + generator_evaluations=[], + next_page_token="def", + ), + generator_evaluation.ListGeneratorEvaluationsResponse( + generator_evaluations=[ + generator_evaluation.GeneratorEvaluation(), + ], + next_page_token="ghi", + ), + generator_evaluation.ListGeneratorEvaluationsResponse( + generator_evaluations=[ + generator_evaluation.GeneratorEvaluation(), + generator_evaluation.GeneratorEvaluation(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_generator_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, generator_evaluation.GeneratorEvaluation) for i in results + ) + + +def test_list_generator_evaluations_pages(transport_name: str = "grpc"): + client = GeneratorEvaluationsClient( + 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_generator_evaluations), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + generator_evaluation.ListGeneratorEvaluationsResponse( + generator_evaluations=[ + generator_evaluation.GeneratorEvaluation(), + generator_evaluation.GeneratorEvaluation(), + generator_evaluation.GeneratorEvaluation(), + ], + next_page_token="abc", + ), + generator_evaluation.ListGeneratorEvaluationsResponse( + generator_evaluations=[], + next_page_token="def", + ), + generator_evaluation.ListGeneratorEvaluationsResponse( + generator_evaluations=[ + generator_evaluation.GeneratorEvaluation(), + ], + next_page_token="ghi", + ), + generator_evaluation.ListGeneratorEvaluationsResponse( + generator_evaluations=[ + generator_evaluation.GeneratorEvaluation(), + generator_evaluation.GeneratorEvaluation(), + ], + ), + RuntimeError, + ) + pages = list(client.list_generator_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_generator_evaluations_async_pager(): + client = GeneratorEvaluationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_generator_evaluations), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + generator_evaluation.ListGeneratorEvaluationsResponse( + generator_evaluations=[ + generator_evaluation.GeneratorEvaluation(), + generator_evaluation.GeneratorEvaluation(), + generator_evaluation.GeneratorEvaluation(), + ], + next_page_token="abc", + ), + generator_evaluation.ListGeneratorEvaluationsResponse( + generator_evaluations=[], + next_page_token="def", + ), + generator_evaluation.ListGeneratorEvaluationsResponse( + generator_evaluations=[ + generator_evaluation.GeneratorEvaluation(), + ], + next_page_token="ghi", + ), + generator_evaluation.ListGeneratorEvaluationsResponse( + generator_evaluations=[ + generator_evaluation.GeneratorEvaluation(), + generator_evaluation.GeneratorEvaluation(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_generator_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, generator_evaluation.GeneratorEvaluation) for i in responses + ) + + +@pytest.mark.asyncio +async def test_list_generator_evaluations_async_pages(): + client = GeneratorEvaluationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_generator_evaluations), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + generator_evaluation.ListGeneratorEvaluationsResponse( + generator_evaluations=[ + generator_evaluation.GeneratorEvaluation(), + generator_evaluation.GeneratorEvaluation(), + generator_evaluation.GeneratorEvaluation(), + ], + next_page_token="abc", + ), + generator_evaluation.ListGeneratorEvaluationsResponse( + generator_evaluations=[], + next_page_token="def", + ), + generator_evaluation.ListGeneratorEvaluationsResponse( + generator_evaluations=[ + generator_evaluation.GeneratorEvaluation(), + ], + next_page_token="ghi", + ), + generator_evaluation.ListGeneratorEvaluationsResponse( + generator_evaluations=[ + generator_evaluation.GeneratorEvaluation(), + generator_evaluation.GeneratorEvaluation(), + ], + ), + 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_generator_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", + [ + generator_evaluation.DeleteGeneratorEvaluationRequest, + dict, + ], +) +def test_delete_generator_evaluation(request_type, transport: str = "grpc"): + client = GeneratorEvaluationsClient( + 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_generator_evaluation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_generator_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = generator_evaluation.DeleteGeneratorEvaluationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_generator_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 = GeneratorEvaluationsClient( + 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 = generator_evaluation.DeleteGeneratorEvaluationRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_generator_evaluation), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_generator_evaluation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == generator_evaluation.DeleteGeneratorEvaluationRequest( + name="name_value", + ) + + +def test_delete_generator_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 = GeneratorEvaluationsClient( + 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_generator_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_generator_evaluation + ] = mock_rpc + request = {} + client.delete_generator_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_generator_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_generator_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 = GeneratorEvaluationsAsyncClient( + 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_generator_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_generator_evaluation + ] = mock_rpc + + request = {} + await client.delete_generator_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_generator_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_generator_evaluation_async( + transport: str = "grpc_asyncio", + request_type=generator_evaluation.DeleteGeneratorEvaluationRequest, +): + client = GeneratorEvaluationsAsyncClient( + 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_generator_evaluation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_generator_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = generator_evaluation.DeleteGeneratorEvaluationRequest() + 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_generator_evaluation_async_from_dict(): + await test_delete_generator_evaluation_async(request_type=dict) + + +def test_delete_generator_evaluation_field_headers(): + client = GeneratorEvaluationsClient( + 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 = generator_evaluation.DeleteGeneratorEvaluationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_generator_evaluation), "__call__" + ) as call: + call.return_value = None + client.delete_generator_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_generator_evaluation_field_headers_async(): + client = GeneratorEvaluationsAsyncClient( + 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 = generator_evaluation.DeleteGeneratorEvaluationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_generator_evaluation), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_generator_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_generator_evaluation_flattened(): + client = GeneratorEvaluationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_generator_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_generator_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_generator_evaluation_flattened_error(): + client = GeneratorEvaluationsClient( + 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_generator_evaluation( + generator_evaluation.DeleteGeneratorEvaluationRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_generator_evaluation_flattened_async(): + client = GeneratorEvaluationsAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_generator_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_generator_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_generator_evaluation_flattened_error_async(): + client = GeneratorEvaluationsAsyncClient( + 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_generator_evaluation( + generator_evaluation.DeleteGeneratorEvaluationRequest(), + name="name_value", + ) + + +def test_create_generator_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 = GeneratorEvaluationsClient( + 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_generator_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_generator_evaluation + ] = mock_rpc + + request = {} + client.create_generator_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.create_generator_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_generator_evaluation_rest_required_fields( + request_type=gcd_generator_evaluation.CreateGeneratorEvaluationRequest, +): + transport_class = transports.GeneratorEvaluationsRestTransport + + 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_generator_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_generator_evaluation._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 = GeneratorEvaluationsClient( + 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_generator_evaluation(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_generator_evaluation_rest_unset_required_fields(): + transport = transports.GeneratorEvaluationsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_generator_evaluation._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "generatorEvaluation", + ) + ) + ) + + +def test_create_generator_evaluation_rest_flattened(): + client = GeneratorEvaluationsClient( + 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/generators/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + generator_evaluation=gcd_generator_evaluation.GeneratorEvaluation( + 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.create_generator_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/v2/{parent=projects/*/locations/*/generators/*}/evaluations" + % client.transport._host, + args[1], + ) + + +def test_create_generator_evaluation_rest_flattened_error(transport: str = "rest"): + client = GeneratorEvaluationsClient( + 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_generator_evaluation( + gcd_generator_evaluation.CreateGeneratorEvaluationRequest(), + parent="parent_value", + generator_evaluation=gcd_generator_evaluation.GeneratorEvaluation( + name="name_value" + ), + ) + + +def test_get_generator_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 = GeneratorEvaluationsClient( + 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_generator_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_generator_evaluation + ] = mock_rpc + + request = {} + client.get_generator_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_generator_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_generator_evaluation_rest_required_fields( + request_type=generator_evaluation.GetGeneratorEvaluationRequest, +): + transport_class = transports.GeneratorEvaluationsRestTransport + + 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_generator_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_generator_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 = GeneratorEvaluationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = generator_evaluation.GeneratorEvaluation() + # 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 = generator_evaluation.GeneratorEvaluation.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_generator_evaluation(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_generator_evaluation_rest_unset_required_fields(): + transport = transports.GeneratorEvaluationsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_generator_evaluation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_generator_evaluation_rest_flattened(): + client = GeneratorEvaluationsClient( + 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 = generator_evaluation.GeneratorEvaluation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/generators/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 = generator_evaluation.GeneratorEvaluation.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_generator_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/v2/{name=projects/*/locations/*/generators/*/evaluations/*}" + % client.transport._host, + args[1], + ) + + +def test_get_generator_evaluation_rest_flattened_error(transport: str = "rest"): + client = GeneratorEvaluationsClient( + 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_generator_evaluation( + generator_evaluation.GetGeneratorEvaluationRequest(), + name="name_value", + ) + + +def test_list_generator_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 = GeneratorEvaluationsClient( + 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_generator_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_generator_evaluations + ] = mock_rpc + + request = {} + client.list_generator_evaluations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_generator_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_generator_evaluations_rest_required_fields( + request_type=generator_evaluation.ListGeneratorEvaluationsRequest, +): + transport_class = transports.GeneratorEvaluationsRestTransport + + 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_generator_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_generator_evaluations._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "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 = GeneratorEvaluationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = generator_evaluation.ListGeneratorEvaluationsResponse() + # 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 = generator_evaluation.ListGeneratorEvaluationsResponse.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_generator_evaluations(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_generator_evaluations_rest_unset_required_fields(): + transport = transports.GeneratorEvaluationsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_generator_evaluations._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_generator_evaluations_rest_flattened(): + client = GeneratorEvaluationsClient( + 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 = generator_evaluation.ListGeneratorEvaluationsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/generators/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 = generator_evaluation.ListGeneratorEvaluationsResponse.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_generator_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/v2/{parent=projects/*/locations/*/generators/*}/evaluations" + % client.transport._host, + args[1], + ) + + +def test_list_generator_evaluations_rest_flattened_error(transport: str = "rest"): + client = GeneratorEvaluationsClient( + 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_generator_evaluations( + generator_evaluation.ListGeneratorEvaluationsRequest(), + parent="parent_value", + ) + + +def test_list_generator_evaluations_rest_pager(transport: str = "rest"): + client = GeneratorEvaluationsClient( + 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 = ( + generator_evaluation.ListGeneratorEvaluationsResponse( + generator_evaluations=[ + generator_evaluation.GeneratorEvaluation(), + generator_evaluation.GeneratorEvaluation(), + generator_evaluation.GeneratorEvaluation(), + ], + next_page_token="abc", + ), + generator_evaluation.ListGeneratorEvaluationsResponse( + generator_evaluations=[], + next_page_token="def", + ), + generator_evaluation.ListGeneratorEvaluationsResponse( + generator_evaluations=[ + generator_evaluation.GeneratorEvaluation(), + ], + next_page_token="ghi", + ), + generator_evaluation.ListGeneratorEvaluationsResponse( + generator_evaluations=[ + generator_evaluation.GeneratorEvaluation(), + generator_evaluation.GeneratorEvaluation(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + generator_evaluation.ListGeneratorEvaluationsResponse.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/generators/sample3" + } + + pager = client.list_generator_evaluations(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, generator_evaluation.GeneratorEvaluation) for i in results + ) + + pages = list(client.list_generator_evaluations(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_delete_generator_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 = GeneratorEvaluationsClient( + 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_generator_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_generator_evaluation + ] = mock_rpc + + request = {} + client.delete_generator_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_generator_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_generator_evaluation_rest_required_fields( + request_type=generator_evaluation.DeleteGeneratorEvaluationRequest, +): + transport_class = transports.GeneratorEvaluationsRestTransport + + 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_generator_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_generator_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 = GeneratorEvaluationsClient( + 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_generator_evaluation(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_generator_evaluation_rest_unset_required_fields(): + transport = transports.GeneratorEvaluationsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_generator_evaluation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_delete_generator_evaluation_rest_flattened(): + client = GeneratorEvaluationsClient( + 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/generators/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_generator_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/v2/{name=projects/*/locations/*/generators/*/evaluations/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_generator_evaluation_rest_flattened_error(transport: str = "rest"): + client = GeneratorEvaluationsClient( + 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_generator_evaluation( + generator_evaluation.DeleteGeneratorEvaluationRequest(), + name="name_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.GeneratorEvaluationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = GeneratorEvaluationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.GeneratorEvaluationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = GeneratorEvaluationsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.GeneratorEvaluationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = GeneratorEvaluationsClient( + 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 = GeneratorEvaluationsClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.GeneratorEvaluationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = GeneratorEvaluationsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.GeneratorEvaluationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = GeneratorEvaluationsClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.GeneratorEvaluationsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.GeneratorEvaluationsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.GeneratorEvaluationsGrpcTransport, + transports.GeneratorEvaluationsGrpcAsyncIOTransport, + transports.GeneratorEvaluationsRestTransport, + ], +) +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 = GeneratorEvaluationsClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = GeneratorEvaluationsClient( + 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_create_generator_evaluation_empty_call_grpc(): + client = GeneratorEvaluationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_generator_evaluation), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_generator_evaluation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcd_generator_evaluation.CreateGeneratorEvaluationRequest() + + 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_generator_evaluation_empty_call_grpc(): + client = GeneratorEvaluationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_generator_evaluation), "__call__" + ) as call: + call.return_value = generator_evaluation.GeneratorEvaluation() + client.get_generator_evaluation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = generator_evaluation.GetGeneratorEvaluationRequest() + + 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_generator_evaluations_empty_call_grpc(): + client = GeneratorEvaluationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_generator_evaluations), "__call__" + ) as call: + call.return_value = generator_evaluation.ListGeneratorEvaluationsResponse() + client.list_generator_evaluations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = generator_evaluation.ListGeneratorEvaluationsRequest() + + 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_generator_evaluation_empty_call_grpc(): + client = GeneratorEvaluationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_generator_evaluation), "__call__" + ) as call: + call.return_value = None + client.delete_generator_evaluation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = generator_evaluation.DeleteGeneratorEvaluationRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = GeneratorEvaluationsAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = GeneratorEvaluationsAsyncClient( + 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_create_generator_evaluation_empty_call_grpc_asyncio(): + client = GeneratorEvaluationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_generator_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.create_generator_evaluation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcd_generator_evaluation.CreateGeneratorEvaluationRequest() + + 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_generator_evaluation_empty_call_grpc_asyncio(): + client = GeneratorEvaluationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_generator_evaluation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + generator_evaluation.GeneratorEvaluation( + name="name_value", + display_name="display_name_value", + satisfies_pzs=True, + satisfies_pzi=True, + ) + ) + await client.get_generator_evaluation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = generator_evaluation.GetGeneratorEvaluationRequest() + + 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_generator_evaluations_empty_call_grpc_asyncio(): + client = GeneratorEvaluationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_generator_evaluations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + generator_evaluation.ListGeneratorEvaluationsResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_generator_evaluations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = generator_evaluation.ListGeneratorEvaluationsRequest() + + 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_generator_evaluation_empty_call_grpc_asyncio(): + client = GeneratorEvaluationsAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_generator_evaluation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_generator_evaluation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = generator_evaluation.DeleteGeneratorEvaluationRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = GeneratorEvaluationsClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_generator_evaluation_rest_bad_request( + request_type=gcd_generator_evaluation.CreateGeneratorEvaluationRequest, +): + client = GeneratorEvaluationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/generators/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_generator_evaluation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + gcd_generator_evaluation.CreateGeneratorEvaluationRequest, + dict, + ], +) +def test_create_generator_evaluation_rest_call_success(request_type): + client = GeneratorEvaluationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/generators/sample3"} + request_init["generator_evaluation"] = { + "name": "name_value", + "display_name": "display_name_value", + "generator_evaluation_config": { + "input_data_config": { + "input_data_source_type": 1, + "start_time": {"seconds": 751, "nanos": 543}, + "end_time": {}, + "sample_size": 1180, + "is_summary_generation_allowed": True, + "summary_generation_option": 1, + "agent_assist_input_data_config": {"start_time": {}, "end_time": {}}, + "dataset_input_data_config": {"dataset": "dataset_value"}, + }, + "output_gcs_bucket_path": "output_gcs_bucket_path_value", + "summarization_config": { + "enable_accuracy_evaluation": True, + "accuracy_evaluation_version": "accuracy_evaluation_version_value", + "enable_completeness_evaluation": True, + "completeness_evaluation_version": "completeness_evaluation_version_value", + "evaluator_version": "evaluator_version_value", + }, + }, + "create_time": {}, + "complete_time": {}, + "initial_generator": { + "name": "name_value", + "description": "description_value", + "free_form_context": {"text": "text_value"}, + "agent_coaching_context": { + "overarching_guidance": "overarching_guidance_value", + "instructions": [ + { + "display_name": "display_name_value", + "display_details": "display_details_value", + "condition": "condition_value", + "agent_action": "agent_action_value", + "system_action": "system_action_value", + "duplicate_check_result": { + "duplicate_suggestions": [ + { + "answer_record": "answer_record_value", + "suggestion_index": 1727, + "similarity_score": 0.17300000000000001, + } + ] + }, + "triggering_event": 1, + } + ], + "version": "version_value", + "output_language_code": "output_language_code_value", + }, + "summarization_context": { + "summarization_sections": [ + {"key": "key_value", "definition": "definition_value", "type_": 1} + ], + "few_shot_examples": [ + { + "conversation_context": { + "message_entries": [ + { + "role": 1, + "text": "text_value", + "language_code": "language_code_value", + "create_time": {}, + } + ] + }, + "extra_info": {}, + "summarization_section_list": {"summarization_sections": {}}, + "output": { + "free_form_suggestion": {"response": "response_value"}, + "summary_suggestion": { + "summary_sections": [ + { + "section": "section_value", + "summary": "summary_value", + } + ] + }, + "agent_coaching_suggestion": { + "applicable_instructions": {}, + "agent_action_suggestions": [ + { + "agent_action": "agent_action_value", + "sources": { + "instruction_indexes": [2066, 2067] + }, + "duplicate_check_result": { + "duplicate_suggestions": [ + { + "answer_record": "answer_record_value", + "sources": {}, + "suggestion_index": 1727, + "similarity_score": 0.17300000000000001, + } + ] + }, + } + ], + "sample_responses": [ + { + "response_text": "response_text_value", + "sources": {}, + "duplicate_check_result": {}, + } + ], + }, + "tool_call_info": [ + { + "tool_call": { + "tool": "tool_value", + "tool_display_name": "tool_display_name_value", + "tool_display_details": "tool_display_details_value", + "action": "action_value", + "input_parameters": {"fields": {}}, + "create_time": {}, + "answer_record": "answer_record_value", + "state": 1, + }, + "tool_call_result": { + "tool": "tool_value", + "action": "action_value", + "error": {"message": "message_value"}, + "raw_content": b"raw_content_blob", + "content": "content_value", + "create_time": {}, + "answer_record": "answer_record_value", + }, + } + ], + }, + } + ], + "version": "version_value", + "output_language_code": "output_language_code_value", + }, + "inference_parameter": { + "max_output_tokens": 1865, + "temperature": 0.1198, + "top_k": 541, + "top_p": 0.546, + }, + "trigger_event": 1, + "published_model": "published_model_value", + "create_time": {}, + "update_time": {}, + "tools": ["tools_value1", "tools_value2"], + "suggestion_deduping_config": { + "enable_deduping": True, + "similarity_threshold": 0.21630000000000002, + }, + }, + "summarization_metrics": { + "summarization_evaluation_results": [ + { + "session_id": "session_id_value", + "metric": "metric_value", + "section": "section_value", + "score": 0.54, + "section_summary": "section_summary_value", + "decompositions": [ + { + "accuracy_decomposition": { + "point": "point_value", + "accuracy_reasoning": "accuracy_reasoning_value", + "is_accurate": True, + }, + "adherence_decomposition": { + "point": "point_value", + "adherence_reasoning": "adherence_reasoning_value", + "is_adherent": True, + }, + } + ], + "evaluation_results": [ + { + "accuracy_decomposition": {}, + "adherence_rubric": { + "question": "question_value", + "reasoning": "reasoning_value", + "is_addressed": True, + }, + "completeness_rubric": { + "question": "question_value", + "is_addressed": True, + }, + } + ], + } + ], + "summarization_evaluation_merged_results_uri": "summarization_evaluation_merged_results_uri_value", + "overall_metrics": [{"metric": "metric_value"}], + "overall_section_tokens": [ + {"section": "section_value", "token_count": 1193} + ], + "conversation_details": [ + { + "message_entries": {}, + "summary_sections": {}, + "metric_details": [ + { + "metric": "metric_value", + "score": 0.54, + "section_details": [ + { + "section": "section_value", + "score": 0.54, + "section_summary": "section_summary_value", + "evaluation_results": {}, + } + ], + } + ], + "section_tokens": {}, + } + ], + }, + "evaluation_status": { + "done": True, + "pipeline_status": { + "code": 411, + "message": "message_value", + "details": [ + { + "type_url": "type.googleapis.com/google.protobuf.Duration", + "value": b"\x08\x0c\x10\xdb\x07", + } + ], + }, + }, + "satisfies_pzs": True, + "satisfies_pzi": 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 = gcd_generator_evaluation.CreateGeneratorEvaluationRequest.meta.fields[ + "generator_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[ + "generator_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["generator_evaluation"][field])): + del request_init["generator_evaluation"][field][i][subfield] + else: + del request_init["generator_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 = 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_generator_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_create_generator_evaluation_rest_interceptors(null_interceptor): + transport = transports.GeneratorEvaluationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.GeneratorEvaluationsRestInterceptor(), + ) + client = GeneratorEvaluationsClient(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.GeneratorEvaluationsRestInterceptor, + "post_create_generator_evaluation", + ) as post, mock.patch.object( + transports.GeneratorEvaluationsRestInterceptor, + "post_create_generator_evaluation_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.GeneratorEvaluationsRestInterceptor, + "pre_create_generator_evaluation", + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcd_generator_evaluation.CreateGeneratorEvaluationRequest.pb( + gcd_generator_evaluation.CreateGeneratorEvaluationRequest() + ) + 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 = gcd_generator_evaluation.CreateGeneratorEvaluationRequest() + 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_generator_evaluation( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_generator_evaluation_rest_bad_request( + request_type=generator_evaluation.GetGeneratorEvaluationRequest, +): + client = GeneratorEvaluationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/generators/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_generator_evaluation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + generator_evaluation.GetGeneratorEvaluationRequest, + dict, + ], +) +def test_get_generator_evaluation_rest_call_success(request_type): + client = GeneratorEvaluationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/generators/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 = generator_evaluation.GeneratorEvaluation( + name="name_value", + display_name="display_name_value", + satisfies_pzs=True, + satisfies_pzi=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 = generator_evaluation.GeneratorEvaluation.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_generator_evaluation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, generator_evaluation.GeneratorEvaluation) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_generator_evaluation_rest_interceptors(null_interceptor): + transport = transports.GeneratorEvaluationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.GeneratorEvaluationsRestInterceptor(), + ) + client = GeneratorEvaluationsClient(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.GeneratorEvaluationsRestInterceptor, "post_get_generator_evaluation" + ) as post, mock.patch.object( + transports.GeneratorEvaluationsRestInterceptor, + "post_get_generator_evaluation_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.GeneratorEvaluationsRestInterceptor, "pre_get_generator_evaluation" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = generator_evaluation.GetGeneratorEvaluationRequest.pb( + generator_evaluation.GetGeneratorEvaluationRequest() + ) + 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 = generator_evaluation.GeneratorEvaluation.to_json( + generator_evaluation.GeneratorEvaluation() + ) + req.return_value.content = return_value + + request = generator_evaluation.GetGeneratorEvaluationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = generator_evaluation.GeneratorEvaluation() + post_with_metadata.return_value = ( + generator_evaluation.GeneratorEvaluation(), + metadata, + ) + + client.get_generator_evaluation( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_generator_evaluations_rest_bad_request( + request_type=generator_evaluation.ListGeneratorEvaluationsRequest, +): + client = GeneratorEvaluationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/generators/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_generator_evaluations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + generator_evaluation.ListGeneratorEvaluationsRequest, + dict, + ], +) +def test_list_generator_evaluations_rest_call_success(request_type): + client = GeneratorEvaluationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/generators/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 = generator_evaluation.ListGeneratorEvaluationsResponse( + 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 = generator_evaluation.ListGeneratorEvaluationsResponse.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_generator_evaluations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListGeneratorEvaluationsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_generator_evaluations_rest_interceptors(null_interceptor): + transport = transports.GeneratorEvaluationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.GeneratorEvaluationsRestInterceptor(), + ) + client = GeneratorEvaluationsClient(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.GeneratorEvaluationsRestInterceptor, + "post_list_generator_evaluations", + ) as post, mock.patch.object( + transports.GeneratorEvaluationsRestInterceptor, + "post_list_generator_evaluations_with_metadata", + ) as post_with_metadata, mock.patch.object( + transports.GeneratorEvaluationsRestInterceptor, "pre_list_generator_evaluations" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = generator_evaluation.ListGeneratorEvaluationsRequest.pb( + generator_evaluation.ListGeneratorEvaluationsRequest() + ) + 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 = generator_evaluation.ListGeneratorEvaluationsResponse.to_json( + generator_evaluation.ListGeneratorEvaluationsResponse() + ) + req.return_value.content = return_value + + request = generator_evaluation.ListGeneratorEvaluationsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = generator_evaluation.ListGeneratorEvaluationsResponse() + post_with_metadata.return_value = ( + generator_evaluation.ListGeneratorEvaluationsResponse(), + metadata, + ) + + client.list_generator_evaluations( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_generator_evaluation_rest_bad_request( + request_type=generator_evaluation.DeleteGeneratorEvaluationRequest, +): + client = GeneratorEvaluationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/generators/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_generator_evaluation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + generator_evaluation.DeleteGeneratorEvaluationRequest, + dict, + ], +) +def test_delete_generator_evaluation_rest_call_success(request_type): + client = GeneratorEvaluationsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/generators/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_generator_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_generator_evaluation_rest_interceptors(null_interceptor): + transport = transports.GeneratorEvaluationsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.GeneratorEvaluationsRestInterceptor(), + ) + client = GeneratorEvaluationsClient(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.GeneratorEvaluationsRestInterceptor, + "pre_delete_generator_evaluation", + ) as pre: + pre.assert_not_called() + pb_message = generator_evaluation.DeleteGeneratorEvaluationRequest.pb( + generator_evaluation.DeleteGeneratorEvaluationRequest() + ) + 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 = generator_evaluation.DeleteGeneratorEvaluationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_generator_evaluation( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = GeneratorEvaluationsClient( + 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 = GeneratorEvaluationsClient( + 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 = GeneratorEvaluationsClient( + 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 = GeneratorEvaluationsClient( + 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 = GeneratorEvaluationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/operations/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.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = GeneratorEvaluationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/operations/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 = 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_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = GeneratorEvaluationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/operations/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_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = GeneratorEvaluationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/operations/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.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 = GeneratorEvaluationsClient( + 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_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = GeneratorEvaluationsClient( + 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 = 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 = GeneratorEvaluationsClient( + 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_create_generator_evaluation_empty_call_rest(): + client = GeneratorEvaluationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_generator_evaluation), "__call__" + ) as call: + client.create_generator_evaluation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcd_generator_evaluation.CreateGeneratorEvaluationRequest() + + 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_generator_evaluation_empty_call_rest(): + client = GeneratorEvaluationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_generator_evaluation), "__call__" + ) as call: + client.get_generator_evaluation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = generator_evaluation.GetGeneratorEvaluationRequest() + + 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_generator_evaluations_empty_call_rest(): + client = GeneratorEvaluationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_generator_evaluations), "__call__" + ) as call: + client.list_generator_evaluations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = generator_evaluation.ListGeneratorEvaluationsRequest() + + 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_generator_evaluation_empty_call_rest(): + client = GeneratorEvaluationsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_generator_evaluation), "__call__" + ) as call: + client.delete_generator_evaluation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = generator_evaluation.DeleteGeneratorEvaluationRequest() + + assert args[0] == request_msg + + +def test_generator_evaluations_rest_lro_client(): + client = GeneratorEvaluationsClient( + 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 = GeneratorEvaluationsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.GeneratorEvaluationsGrpcTransport, + ) + + +def test_generator_evaluations_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.GeneratorEvaluationsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_generator_evaluations_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.dialogflow_v2.services.generator_evaluations.transports.GeneratorEvaluationsTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.GeneratorEvaluationsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "create_generator_evaluation", + "get_generator_evaluation", + "list_generator_evaluations", + "delete_generator_evaluation", + "get_location", + "list_locations", + "get_operation", + "cancel_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_generator_evaluations_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.dialogflow_v2.services.generator_evaluations.transports.GeneratorEvaluationsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.GeneratorEvaluationsTransport( + 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/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +def test_generator_evaluations_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.dialogflow_v2.services.generator_evaluations.transports.GeneratorEvaluationsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.GeneratorEvaluationsTransport() + adc.assert_called_once() + + +def test_generator_evaluations_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) + GeneratorEvaluationsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.GeneratorEvaluationsGrpcTransport, + transports.GeneratorEvaluationsGrpcAsyncIOTransport, + ], +) +def test_generator_evaluations_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/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.GeneratorEvaluationsGrpcTransport, + transports.GeneratorEvaluationsGrpcAsyncIOTransport, + transports.GeneratorEvaluationsRestTransport, + ], +) +def test_generator_evaluations_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.GeneratorEvaluationsGrpcTransport, grpc_helpers), + (transports.GeneratorEvaluationsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_generator_evaluations_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( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.GeneratorEvaluationsGrpcTransport, + transports.GeneratorEvaluationsGrpcAsyncIOTransport, + ], +) +def test_generator_evaluations_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_generator_evaluations_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.GeneratorEvaluationsRestTransport( + 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_generator_evaluations_host_no_port(transport_name): + client = GeneratorEvaluationsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "dialogflow.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://dialogflow.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_generator_evaluations_host_with_port(transport_name): + client = GeneratorEvaluationsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "dialogflow.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://dialogflow.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_generator_evaluations_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = GeneratorEvaluationsClient( + credentials=creds1, + transport=transport_name, + ) + client2 = GeneratorEvaluationsClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_generator_evaluation._session + session2 = client2.transport.create_generator_evaluation._session + assert session1 != session2 + session1 = client1.transport.get_generator_evaluation._session + session2 = client2.transport.get_generator_evaluation._session + assert session1 != session2 + session1 = client1.transport.list_generator_evaluations._session + session2 = client2.transport.list_generator_evaluations._session + assert session1 != session2 + session1 = client1.transport.delete_generator_evaluation._session + session2 = client2.transport.delete_generator_evaluation._session + assert session1 != session2 + + +def test_generator_evaluations_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.GeneratorEvaluationsGrpcTransport( + 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_generator_evaluations_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.GeneratorEvaluationsGrpcAsyncIOTransport( + 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.GeneratorEvaluationsGrpcTransport, + transports.GeneratorEvaluationsGrpcAsyncIOTransport, + ], +) +def test_generator_evaluations_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.GeneratorEvaluationsGrpcTransport, + transports.GeneratorEvaluationsGrpcAsyncIOTransport, + ], +) +def test_generator_evaluations_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_generator_evaluations_grpc_lro_client(): + client = GeneratorEvaluationsClient( + 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_generator_evaluations_grpc_lro_async_client(): + client = GeneratorEvaluationsAsyncClient( + 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_generator_path(): + project = "squid" + location = "clam" + generator = "whelk" + expected = "projects/{project}/locations/{location}/generators/{generator}".format( + project=project, + location=location, + generator=generator, + ) + actual = GeneratorEvaluationsClient.generator_path(project, location, generator) + assert expected == actual + + +def test_parse_generator_path(): + expected = { + "project": "octopus", + "location": "oyster", + "generator": "nudibranch", + } + path = GeneratorEvaluationsClient.generator_path(**expected) + + # Check that the path construction is reversible. + actual = GeneratorEvaluationsClient.parse_generator_path(path) + assert expected == actual + + +def test_generator_evaluation_path(): + project = "cuttlefish" + location = "mussel" + generator = "winkle" + evaluation = "nautilus" + expected = "projects/{project}/locations/{location}/generators/{generator}/evaluations/{evaluation}".format( + project=project, + location=location, + generator=generator, + evaluation=evaluation, + ) + actual = GeneratorEvaluationsClient.generator_evaluation_path( + project, location, generator, evaluation + ) + assert expected == actual + + +def test_parse_generator_evaluation_path(): + expected = { + "project": "scallop", + "location": "abalone", + "generator": "squid", + "evaluation": "clam", + } + path = GeneratorEvaluationsClient.generator_evaluation_path(**expected) + + # Check that the path construction is reversible. + actual = GeneratorEvaluationsClient.parse_generator_evaluation_path(path) + assert expected == actual + + +def test_tool_path(): + project = "whelk" + location = "octopus" + tool = "oyster" + expected = "projects/{project}/locations/{location}/tools/{tool}".format( + project=project, + location=location, + tool=tool, + ) + actual = GeneratorEvaluationsClient.tool_path(project, location, tool) + assert expected == actual + + +def test_parse_tool_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "tool": "mussel", + } + path = GeneratorEvaluationsClient.tool_path(**expected) + + # Check that the path construction is reversible. + actual = GeneratorEvaluationsClient.parse_tool_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = GeneratorEvaluationsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = GeneratorEvaluationsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = GeneratorEvaluationsClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = GeneratorEvaluationsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = GeneratorEvaluationsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = GeneratorEvaluationsClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = GeneratorEvaluationsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = GeneratorEvaluationsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = GeneratorEvaluationsClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format( + project=project, + ) + actual = GeneratorEvaluationsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = GeneratorEvaluationsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = GeneratorEvaluationsClient.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 = GeneratorEvaluationsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = GeneratorEvaluationsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = GeneratorEvaluationsClient.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.GeneratorEvaluationsTransport, "_prep_wrapped_messages" + ) as prep: + client = GeneratorEvaluationsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.GeneratorEvaluationsTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = GeneratorEvaluationsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_cancel_operation(transport: str = "grpc"): + client = GeneratorEvaluationsClient( + 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 = GeneratorEvaluationsAsyncClient( + 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 = GeneratorEvaluationsClient( + 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 = GeneratorEvaluationsAsyncClient( + 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 = GeneratorEvaluationsClient( + 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 = GeneratorEvaluationsAsyncClient( + 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 = GeneratorEvaluationsClient( + 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 = GeneratorEvaluationsAsyncClient( + 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 = GeneratorEvaluationsClient( + 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 = GeneratorEvaluationsAsyncClient( + 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 = GeneratorEvaluationsClient( + 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 = GeneratorEvaluationsAsyncClient( + 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 = GeneratorEvaluationsClient( + 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 = GeneratorEvaluationsAsyncClient( + 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 = GeneratorEvaluationsClient( + 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 = GeneratorEvaluationsAsyncClient( + 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 = GeneratorEvaluationsClient( + 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 = GeneratorEvaluationsAsyncClient( + 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 = GeneratorEvaluationsClient( + 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 = GeneratorEvaluationsAsyncClient( + 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 = GeneratorEvaluationsClient( + 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 = GeneratorEvaluationsAsyncClient( + 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 = GeneratorEvaluationsClient( + 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 = GeneratorEvaluationsAsyncClient( + 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 = GeneratorEvaluationsClient( + 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 = GeneratorEvaluationsAsyncClient( + 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 = GeneratorEvaluationsClient( + 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 = GeneratorEvaluationsAsyncClient(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 = GeneratorEvaluationsClient( + 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 = GeneratorEvaluationsAsyncClient( + 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 = GeneratorEvaluationsClient( + 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 = GeneratorEvaluationsAsyncClient( + 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 = GeneratorEvaluationsClient( + 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 = GeneratorEvaluationsClient( + 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", + [ + (GeneratorEvaluationsClient, transports.GeneratorEvaluationsGrpcTransport), + ( + GeneratorEvaluationsAsyncClient, + transports.GeneratorEvaluationsGrpcAsyncIOTransport, + ), + ], +) +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-dialogflow/tests/unit/gapic/dialogflow_v2/test_generators.py b/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2/test_generators.py index 7f66f23ddb17..291ea8b98b66 100644 --- a/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2/test_generators.py +++ b/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2/test_generators.py @@ -54,6 +54,7 @@ from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore from google.cloud.dialogflow_v2.services.generators import ( @@ -62,8 +63,10 @@ pagers, transports, ) +from google.cloud.dialogflow_v2.types import agent_coaching_instruction from google.cloud.dialogflow_v2.types import generator from google.cloud.dialogflow_v2.types import generator as gcd_generator +from google.cloud.dialogflow_v2.types import tool_call CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -1297,6 +1300,7 @@ def test_create_generator(request_type, transport: str = "grpc"): name="name_value", description="description_value", trigger_event=gcd_generator.TriggerEvent.END_OF_UTTERANCE, + tools=["tools_value"], published_model="published_model_value", ) response = client.create_generator(request) @@ -1312,6 +1316,7 @@ def test_create_generator(request_type, transport: str = "grpc"): assert response.name == "name_value" assert response.description == "description_value" assert response.trigger_event == gcd_generator.TriggerEvent.END_OF_UTTERANCE + assert response.tools == ["tools_value"] def test_create_generator_non_empty_request_with_auto_populated_field(): @@ -1444,6 +1449,7 @@ async def test_create_generator_async( name="name_value", description="description_value", trigger_event=gcd_generator.TriggerEvent.END_OF_UTTERANCE, + tools=["tools_value"], ) ) response = await client.create_generator(request) @@ -1459,6 +1465,7 @@ async def test_create_generator_async( assert response.name == "name_value" assert response.description == "description_value" assert response.trigger_event == gcd_generator.TriggerEvent.END_OF_UTTERANCE + assert response.tools == ["tools_value"] @pytest.mark.asyncio @@ -1653,6 +1660,7 @@ def test_get_generator(request_type, transport: str = "grpc"): name="name_value", description="description_value", trigger_event=generator.TriggerEvent.END_OF_UTTERANCE, + tools=["tools_value"], published_model="published_model_value", ) response = client.get_generator(request) @@ -1668,6 +1676,7 @@ def test_get_generator(request_type, transport: str = "grpc"): assert response.name == "name_value" assert response.description == "description_value" assert response.trigger_event == generator.TriggerEvent.END_OF_UTTERANCE + assert response.tools == ["tools_value"] def test_get_generator_non_empty_request_with_auto_populated_field(): @@ -1796,6 +1805,7 @@ async def test_get_generator_async( name="name_value", description="description_value", trigger_event=generator.TriggerEvent.END_OF_UTTERANCE, + tools=["tools_value"], ) ) response = await client.get_generator(request) @@ -1811,6 +1821,7 @@ async def test_get_generator_async( assert response.name == "name_value" assert response.description == "description_value" assert response.trigger_event == generator.TriggerEvent.END_OF_UTTERANCE + assert response.tools == ["tools_value"] @pytest.mark.asyncio @@ -2813,6 +2824,7 @@ def test_update_generator(request_type, transport: str = "grpc"): name="name_value", description="description_value", trigger_event=gcd_generator.TriggerEvent.END_OF_UTTERANCE, + tools=["tools_value"], published_model="published_model_value", ) response = client.update_generator(request) @@ -2828,6 +2840,7 @@ def test_update_generator(request_type, transport: str = "grpc"): assert response.name == "name_value" assert response.description == "description_value" assert response.trigger_event == gcd_generator.TriggerEvent.END_OF_UTTERANCE + assert response.tools == ["tools_value"] def test_update_generator_non_empty_request_with_auto_populated_field(): @@ -2954,6 +2967,7 @@ async def test_update_generator_async( name="name_value", description="description_value", trigger_event=gcd_generator.TriggerEvent.END_OF_UTTERANCE, + tools=["tools_value"], ) ) response = await client.update_generator(request) @@ -2969,6 +2983,7 @@ async def test_update_generator_async( assert response.name == "name_value" assert response.description == "description_value" assert response.trigger_event == gcd_generator.TriggerEvent.END_OF_UTTERANCE + assert response.tools == ["tools_value"] @pytest.mark.asyncio @@ -4355,6 +4370,7 @@ async def test_create_generator_empty_call_grpc_asyncio(): name="name_value", description="description_value", trigger_event=gcd_generator.TriggerEvent.END_OF_UTTERANCE, + tools=["tools_value"], ) ) await client.create_generator(request=None) @@ -4384,6 +4400,7 @@ async def test_get_generator_empty_call_grpc_asyncio(): name="name_value", description="description_value", trigger_event=generator.TriggerEvent.END_OF_UTTERANCE, + tools=["tools_value"], ) ) await client.get_generator(request=None) @@ -4463,6 +4480,7 @@ async def test_update_generator_empty_call_grpc_asyncio(): name="name_value", description="description_value", trigger_event=gcd_generator.TriggerEvent.END_OF_UTTERANCE, + tools=["tools_value"], ) ) await client.update_generator(request=None) @@ -4525,6 +4543,30 @@ def test_create_generator_rest_call_success(request_type): "name": "name_value", "description": "description_value", "free_form_context": {"text": "text_value"}, + "agent_coaching_context": { + "overarching_guidance": "overarching_guidance_value", + "instructions": [ + { + "display_name": "display_name_value", + "display_details": "display_details_value", + "condition": "condition_value", + "agent_action": "agent_action_value", + "system_action": "system_action_value", + "duplicate_check_result": { + "duplicate_suggestions": [ + { + "answer_record": "answer_record_value", + "suggestion_index": 1727, + "similarity_score": 0.17300000000000001, + } + ] + }, + "triggering_event": 1, + } + ], + "version": "version_value", + "output_language_code": "output_language_code_value", + }, "summarization_context": { "summarization_sections": [ {"key": "key_value", "definition": "definition_value", "type_": 1} @@ -4550,6 +4592,55 @@ def test_create_generator_rest_call_success(request_type): {"section": "section_value", "summary": "summary_value"} ] }, + "agent_coaching_suggestion": { + "applicable_instructions": {}, + "agent_action_suggestions": [ + { + "agent_action": "agent_action_value", + "sources": {"instruction_indexes": [2066, 2067]}, + "duplicate_check_result": { + "duplicate_suggestions": [ + { + "answer_record": "answer_record_value", + "sources": {}, + "suggestion_index": 1727, + "similarity_score": 0.17300000000000001, + } + ] + }, + } + ], + "sample_responses": [ + { + "response_text": "response_text_value", + "sources": {}, + "duplicate_check_result": {}, + } + ], + }, + "tool_call_info": [ + { + "tool_call": { + "tool": "tool_value", + "tool_display_name": "tool_display_name_value", + "tool_display_details": "tool_display_details_value", + "action": "action_value", + "input_parameters": {"fields": {}}, + "create_time": {}, + "answer_record": "answer_record_value", + "state": 1, + }, + "tool_call_result": { + "tool": "tool_value", + "action": "action_value", + "error": {"message": "message_value"}, + "raw_content": b"raw_content_blob", + "content": "content_value", + "create_time": {}, + "answer_record": "answer_record_value", + }, + } + ], }, } ], @@ -4566,6 +4657,11 @@ def test_create_generator_rest_call_success(request_type): "published_model": "published_model_value", "create_time": {}, "update_time": {}, + "tools": ["tools_value1", "tools_value2"], + "suggestion_deduping_config": { + "enable_deduping": True, + "similarity_threshold": 0.21630000000000002, + }, } # 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 @@ -4643,6 +4739,7 @@ def get_message_fields(field): name="name_value", description="description_value", trigger_event=gcd_generator.TriggerEvent.END_OF_UTTERANCE, + tools=["tools_value"], published_model="published_model_value", ) @@ -4663,6 +4760,7 @@ def get_message_fields(field): assert response.name == "name_value" assert response.description == "description_value" assert response.trigger_event == gcd_generator.TriggerEvent.END_OF_UTTERANCE + assert response.tools == ["tools_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -4773,6 +4871,7 @@ def test_get_generator_rest_call_success(request_type): name="name_value", description="description_value", trigger_event=generator.TriggerEvent.END_OF_UTTERANCE, + tools=["tools_value"], published_model="published_model_value", ) @@ -4793,6 +4892,7 @@ def test_get_generator_rest_call_success(request_type): assert response.name == "name_value" assert response.description == "description_value" assert response.trigger_event == generator.TriggerEvent.END_OF_UTTERANCE + assert response.tools == ["tools_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -5138,6 +5238,30 @@ def test_update_generator_rest_call_success(request_type): "name": "projects/sample1/locations/sample2/generators/sample3", "description": "description_value", "free_form_context": {"text": "text_value"}, + "agent_coaching_context": { + "overarching_guidance": "overarching_guidance_value", + "instructions": [ + { + "display_name": "display_name_value", + "display_details": "display_details_value", + "condition": "condition_value", + "agent_action": "agent_action_value", + "system_action": "system_action_value", + "duplicate_check_result": { + "duplicate_suggestions": [ + { + "answer_record": "answer_record_value", + "suggestion_index": 1727, + "similarity_score": 0.17300000000000001, + } + ] + }, + "triggering_event": 1, + } + ], + "version": "version_value", + "output_language_code": "output_language_code_value", + }, "summarization_context": { "summarization_sections": [ {"key": "key_value", "definition": "definition_value", "type_": 1} @@ -5163,6 +5287,55 @@ def test_update_generator_rest_call_success(request_type): {"section": "section_value", "summary": "summary_value"} ] }, + "agent_coaching_suggestion": { + "applicable_instructions": {}, + "agent_action_suggestions": [ + { + "agent_action": "agent_action_value", + "sources": {"instruction_indexes": [2066, 2067]}, + "duplicate_check_result": { + "duplicate_suggestions": [ + { + "answer_record": "answer_record_value", + "sources": {}, + "suggestion_index": 1727, + "similarity_score": 0.17300000000000001, + } + ] + }, + } + ], + "sample_responses": [ + { + "response_text": "response_text_value", + "sources": {}, + "duplicate_check_result": {}, + } + ], + }, + "tool_call_info": [ + { + "tool_call": { + "tool": "tool_value", + "tool_display_name": "tool_display_name_value", + "tool_display_details": "tool_display_details_value", + "action": "action_value", + "input_parameters": {"fields": {}}, + "create_time": {}, + "answer_record": "answer_record_value", + "state": 1, + }, + "tool_call_result": { + "tool": "tool_value", + "action": "action_value", + "error": {"message": "message_value"}, + "raw_content": b"raw_content_blob", + "content": "content_value", + "create_time": {}, + "answer_record": "answer_record_value", + }, + } + ], }, } ], @@ -5179,6 +5352,11 @@ def test_update_generator_rest_call_success(request_type): "published_model": "published_model_value", "create_time": {}, "update_time": {}, + "tools": ["tools_value1", "tools_value2"], + "suggestion_deduping_config": { + "enable_deduping": True, + "similarity_threshold": 0.21630000000000002, + }, } # 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 @@ -5256,6 +5434,7 @@ def get_message_fields(field): name="name_value", description="description_value", trigger_event=gcd_generator.TriggerEvent.END_OF_UTTERANCE, + tools=["tools_value"], published_model="published_model_value", ) @@ -5276,6 +5455,7 @@ def get_message_fields(field): assert response.name == "name_value" assert response.description == "description_value" assert response.trigger_event == gcd_generator.TriggerEvent.END_OF_UTTERANCE + assert response.tools == ["tools_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -6223,8 +6403,34 @@ def test_parse_generator_path(): assert expected == actual +def test_tool_path(): + project = "cuttlefish" + location = "mussel" + tool = "winkle" + expected = "projects/{project}/locations/{location}/tools/{tool}".format( + project=project, + location=location, + tool=tool, + ) + actual = GeneratorsClient.tool_path(project, location, tool) + assert expected == actual + + +def test_parse_tool_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "tool": "abalone", + } + path = GeneratorsClient.tool_path(**expected) + + # Check that the path construction is reversible. + actual = GeneratorsClient.parse_tool_path(path) + assert expected == actual + + def test_common_billing_account_path(): - billing_account = "cuttlefish" + billing_account = "squid" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -6234,7 +6440,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "mussel", + "billing_account": "clam", } path = GeneratorsClient.common_billing_account_path(**expected) @@ -6244,7 +6450,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "winkle" + folder = "whelk" expected = "folders/{folder}".format( folder=folder, ) @@ -6254,7 +6460,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "nautilus", + "folder": "octopus", } path = GeneratorsClient.common_folder_path(**expected) @@ -6264,7 +6470,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "scallop" + organization = "oyster" expected = "organizations/{organization}".format( organization=organization, ) @@ -6274,7 +6480,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "abalone", + "organization": "nudibranch", } path = GeneratorsClient.common_organization_path(**expected) @@ -6284,7 +6490,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "squid" + project = "cuttlefish" expected = "projects/{project}".format( project=project, ) @@ -6294,7 +6500,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "clam", + "project": "mussel", } path = GeneratorsClient.common_project_path(**expected) @@ -6304,8 +6510,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "whelk" - location = "octopus" + project = "winkle" + location = "nautilus" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -6316,8 +6522,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "oyster", - "location": "nudibranch", + "project": "scallop", + "location": "abalone", } path = GeneratorsClient.common_location_path(**expected) diff --git a/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2/test_participants.py b/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2/test_participants.py index 26fb147265af..a6f31b15210a 100644 --- a/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2/test_participants.py +++ b/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2/test_participants.py @@ -55,6 +55,7 @@ from google.oauth2 import service_account from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore from google.type import latlng_pb2 # type: ignore from google.cloud.dialogflow_v2.services.participants import ( @@ -1321,6 +1322,7 @@ def test_create_participant(request_type, transport: str = "grpc"): role=gcd_participant.Participant.Role.HUMAN_AGENT, sip_recording_media_label="sip_recording_media_label_value", obfuscated_external_user_id="obfuscated_external_user_id_value", + agent_desktop_source=gcd_participant.Participant.AgentDesktopSource.LIVE_PERSON, ) response = client.create_participant(request) @@ -1336,6 +1338,10 @@ def test_create_participant(request_type, transport: str = "grpc"): assert response.role == gcd_participant.Participant.Role.HUMAN_AGENT assert response.sip_recording_media_label == "sip_recording_media_label_value" assert response.obfuscated_external_user_id == "obfuscated_external_user_id_value" + assert ( + response.agent_desktop_source + == gcd_participant.Participant.AgentDesktopSource.LIVE_PERSON + ) def test_create_participant_non_empty_request_with_auto_populated_field(): @@ -1474,6 +1480,7 @@ async def test_create_participant_async( role=gcd_participant.Participant.Role.HUMAN_AGENT, sip_recording_media_label="sip_recording_media_label_value", obfuscated_external_user_id="obfuscated_external_user_id_value", + agent_desktop_source=gcd_participant.Participant.AgentDesktopSource.LIVE_PERSON, ) ) response = await client.create_participant(request) @@ -1490,6 +1497,10 @@ async def test_create_participant_async( assert response.role == gcd_participant.Participant.Role.HUMAN_AGENT assert response.sip_recording_media_label == "sip_recording_media_label_value" assert response.obfuscated_external_user_id == "obfuscated_external_user_id_value" + assert ( + response.agent_desktop_source + == gcd_participant.Participant.AgentDesktopSource.LIVE_PERSON + ) @pytest.mark.asyncio @@ -1683,6 +1694,7 @@ def test_get_participant(request_type, transport: str = "grpc"): role=participant.Participant.Role.HUMAN_AGENT, sip_recording_media_label="sip_recording_media_label_value", obfuscated_external_user_id="obfuscated_external_user_id_value", + agent_desktop_source=participant.Participant.AgentDesktopSource.LIVE_PERSON, ) response = client.get_participant(request) @@ -1698,6 +1710,10 @@ def test_get_participant(request_type, transport: str = "grpc"): assert response.role == participant.Participant.Role.HUMAN_AGENT assert response.sip_recording_media_label == "sip_recording_media_label_value" assert response.obfuscated_external_user_id == "obfuscated_external_user_id_value" + assert ( + response.agent_desktop_source + == participant.Participant.AgentDesktopSource.LIVE_PERSON + ) def test_get_participant_non_empty_request_with_auto_populated_field(): @@ -1827,6 +1843,7 @@ async def test_get_participant_async( role=participant.Participant.Role.HUMAN_AGENT, sip_recording_media_label="sip_recording_media_label_value", obfuscated_external_user_id="obfuscated_external_user_id_value", + agent_desktop_source=participant.Participant.AgentDesktopSource.LIVE_PERSON, ) ) response = await client.get_participant(request) @@ -1843,6 +1860,10 @@ async def test_get_participant_async( assert response.role == participant.Participant.Role.HUMAN_AGENT assert response.sip_recording_media_label == "sip_recording_media_label_value" assert response.obfuscated_external_user_id == "obfuscated_external_user_id_value" + assert ( + response.agent_desktop_source + == participant.Participant.AgentDesktopSource.LIVE_PERSON + ) @pytest.mark.asyncio @@ -2563,6 +2584,7 @@ def test_update_participant(request_type, transport: str = "grpc"): role=gcd_participant.Participant.Role.HUMAN_AGENT, sip_recording_media_label="sip_recording_media_label_value", obfuscated_external_user_id="obfuscated_external_user_id_value", + agent_desktop_source=gcd_participant.Participant.AgentDesktopSource.LIVE_PERSON, ) response = client.update_participant(request) @@ -2578,6 +2600,10 @@ def test_update_participant(request_type, transport: str = "grpc"): assert response.role == gcd_participant.Participant.Role.HUMAN_AGENT assert response.sip_recording_media_label == "sip_recording_media_label_value" assert response.obfuscated_external_user_id == "obfuscated_external_user_id_value" + assert ( + response.agent_desktop_source + == gcd_participant.Participant.AgentDesktopSource.LIVE_PERSON + ) def test_update_participant_non_empty_request_with_auto_populated_field(): @@ -2712,6 +2738,7 @@ async def test_update_participant_async( role=gcd_participant.Participant.Role.HUMAN_AGENT, sip_recording_media_label="sip_recording_media_label_value", obfuscated_external_user_id="obfuscated_external_user_id_value", + agent_desktop_source=gcd_participant.Participant.AgentDesktopSource.LIVE_PERSON, ) ) response = await client.update_participant(request) @@ -2728,6 +2755,10 @@ async def test_update_participant_async( assert response.role == gcd_participant.Participant.Role.HUMAN_AGENT assert response.sip_recording_media_label == "sip_recording_media_label_value" assert response.obfuscated_external_user_id == "obfuscated_external_user_id_value" + assert ( + response.agent_desktop_source + == gcd_participant.Participant.AgentDesktopSource.LIVE_PERSON + ) @pytest.mark.asyncio @@ -6767,6 +6798,7 @@ async def test_create_participant_empty_call_grpc_asyncio(): role=gcd_participant.Participant.Role.HUMAN_AGENT, sip_recording_media_label="sip_recording_media_label_value", obfuscated_external_user_id="obfuscated_external_user_id_value", + agent_desktop_source=gcd_participant.Participant.AgentDesktopSource.LIVE_PERSON, ) ) await client.create_participant(request=None) @@ -6797,6 +6829,7 @@ async def test_get_participant_empty_call_grpc_asyncio(): role=participant.Participant.Role.HUMAN_AGENT, sip_recording_media_label="sip_recording_media_label_value", obfuscated_external_user_id="obfuscated_external_user_id_value", + agent_desktop_source=participant.Participant.AgentDesktopSource.LIVE_PERSON, ) ) await client.get_participant(request=None) @@ -6858,6 +6891,7 @@ async def test_update_participant_empty_call_grpc_asyncio(): role=gcd_participant.Participant.Role.HUMAN_AGENT, sip_recording_media_label="sip_recording_media_label_value", obfuscated_external_user_id="obfuscated_external_user_id_value", + agent_desktop_source=gcd_participant.Participant.AgentDesktopSource.LIVE_PERSON, ) ) await client.update_participant(request=None) @@ -7067,6 +7101,7 @@ def test_create_participant_rest_call_success(request_type): "sip_recording_media_label": "sip_recording_media_label_value", "obfuscated_external_user_id": "obfuscated_external_user_id_value", "documents_metadata_filters": {}, + "agent_desktop_source": 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 @@ -7145,6 +7180,7 @@ def get_message_fields(field): role=gcd_participant.Participant.Role.HUMAN_AGENT, sip_recording_media_label="sip_recording_media_label_value", obfuscated_external_user_id="obfuscated_external_user_id_value", + agent_desktop_source=gcd_participant.Participant.AgentDesktopSource.LIVE_PERSON, ) # Wrap the value into a proper Response obj @@ -7165,6 +7201,10 @@ def get_message_fields(field): assert response.role == gcd_participant.Participant.Role.HUMAN_AGENT assert response.sip_recording_media_label == "sip_recording_media_label_value" assert response.obfuscated_external_user_id == "obfuscated_external_user_id_value" + assert ( + response.agent_desktop_source + == gcd_participant.Participant.AgentDesktopSource.LIVE_PERSON + ) @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -7284,6 +7324,7 @@ def test_get_participant_rest_call_success(request_type): role=participant.Participant.Role.HUMAN_AGENT, sip_recording_media_label="sip_recording_media_label_value", obfuscated_external_user_id="obfuscated_external_user_id_value", + agent_desktop_source=participant.Participant.AgentDesktopSource.LIVE_PERSON, ) # Wrap the value into a proper Response obj @@ -7304,6 +7345,10 @@ def test_get_participant_rest_call_success(request_type): assert response.role == participant.Participant.Role.HUMAN_AGENT assert response.sip_recording_media_label == "sip_recording_media_label_value" assert response.obfuscated_external_user_id == "obfuscated_external_user_id_value" + assert ( + response.agent_desktop_source + == participant.Participant.AgentDesktopSource.LIVE_PERSON + ) @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -7553,6 +7598,7 @@ def test_update_participant_rest_call_success(request_type): "sip_recording_media_label": "sip_recording_media_label_value", "obfuscated_external_user_id": "obfuscated_external_user_id_value", "documents_metadata_filters": {}, + "agent_desktop_source": 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 @@ -7631,6 +7677,7 @@ def get_message_fields(field): role=gcd_participant.Participant.Role.HUMAN_AGENT, sip_recording_media_label="sip_recording_media_label_value", obfuscated_external_user_id="obfuscated_external_user_id_value", + agent_desktop_source=gcd_participant.Participant.AgentDesktopSource.LIVE_PERSON, ) # Wrap the value into a proper Response obj @@ -7651,6 +7698,10 @@ def get_message_fields(field): assert response.role == gcd_participant.Participant.Role.HUMAN_AGENT assert response.sip_recording_media_label == "sip_recording_media_label_value" assert response.obfuscated_external_user_id == "obfuscated_external_user_id_value" + assert ( + response.agent_desktop_source + == gcd_participant.Participant.AgentDesktopSource.LIVE_PERSON + ) @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -9568,8 +9619,34 @@ def test_parse_session_entity_type_path(): assert expected == actual +def test_tool_path(): + project = "whelk" + location = "octopus" + tool = "oyster" + expected = "projects/{project}/locations/{location}/tools/{tool}".format( + project=project, + location=location, + tool=tool, + ) + actual = ParticipantsClient.tool_path(project, location, tool) + assert expected == actual + + +def test_parse_tool_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "tool": "mussel", + } + path = ParticipantsClient.tool_path(**expected) + + # Check that the path construction is reversible. + actual = ParticipantsClient.parse_tool_path(path) + assert expected == actual + + def test_common_billing_account_path(): - billing_account = "whelk" + billing_account = "winkle" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -9579,7 +9656,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "octopus", + "billing_account": "nautilus", } path = ParticipantsClient.common_billing_account_path(**expected) @@ -9589,7 +9666,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "oyster" + folder = "scallop" expected = "folders/{folder}".format( folder=folder, ) @@ -9599,7 +9676,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "nudibranch", + "folder": "abalone", } path = ParticipantsClient.common_folder_path(**expected) @@ -9609,7 +9686,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "cuttlefish" + organization = "squid" expected = "organizations/{organization}".format( organization=organization, ) @@ -9619,7 +9696,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "mussel", + "organization": "clam", } path = ParticipantsClient.common_organization_path(**expected) @@ -9629,7 +9706,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "winkle" + project = "whelk" expected = "projects/{project}".format( project=project, ) @@ -9639,7 +9716,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "nautilus", + "project": "octopus", } path = ParticipantsClient.common_project_path(**expected) @@ -9649,8 +9726,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "scallop" - location = "abalone" + project = "oyster" + location = "nudibranch" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -9661,8 +9738,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "squid", - "location": "clam", + "project": "cuttlefish", + "location": "mussel", } path = ParticipantsClient.common_location_path(**expected) diff --git a/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2/test_sip_trunks.py b/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2/test_sip_trunks.py new file mode 100644 index 000000000000..11e5e9abde37 --- /dev/null +++ b/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2/test_sip_trunks.py @@ -0,0 +1,7055 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +from collections.abc import AsyncIterable, Iterable +import json +import math + +from google.api_core import api_core_version +from google.protobuf import json_format +import grpc +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest +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 + +from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +import google.auth +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.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.dialogflow_v2.services.sip_trunks import ( + SipTrunksAsyncClient, + SipTrunksClient, + pagers, + transports, +) +from google.cloud.dialogflow_v2.types import sip_trunk +from google.cloud.dialogflow_v2.types import sip_trunk as gcd_sip_trunk + +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 SipTrunksClient._get_default_mtls_endpoint(None) is None + assert SipTrunksClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ( + SipTrunksClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + SipTrunksClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + SipTrunksClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert SipTrunksClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +def test__read_environment_variables(): + assert SipTrunksClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert SipTrunksClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert SipTrunksClient._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: + SipTrunksClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + else: + assert SipTrunksClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert SipTrunksClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert SipTrunksClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert SipTrunksClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + SipTrunksClient._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 SipTrunksClient._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 SipTrunksClient._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 SipTrunksClient._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 SipTrunksClient._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 SipTrunksClient._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 SipTrunksClient._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 SipTrunksClient._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 SipTrunksClient._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 SipTrunksClient._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 SipTrunksClient._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): + SipTrunksClient._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 SipTrunksClient._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 SipTrunksClient._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 SipTrunksClient._get_client_cert_source(None, False) is None + assert ( + SipTrunksClient._get_client_cert_source(mock_provided_cert_source, False) + is None + ) + assert ( + SipTrunksClient._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 ( + SipTrunksClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + SipTrunksClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + SipTrunksClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SipTrunksClient), +) +@mock.patch.object( + SipTrunksAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SipTrunksAsyncClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = SipTrunksClient._DEFAULT_UNIVERSE + default_endpoint = SipTrunksClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = SipTrunksClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + SipTrunksClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + SipTrunksClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == SipTrunksClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + SipTrunksClient._get_api_endpoint(None, None, default_universe, "auto") + == default_endpoint + ) + assert ( + SipTrunksClient._get_api_endpoint(None, None, default_universe, "always") + == SipTrunksClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + SipTrunksClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == SipTrunksClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + SipTrunksClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + SipTrunksClient._get_api_endpoint(None, None, default_universe, "never") + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + SipTrunksClient._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 ( + SipTrunksClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + SipTrunksClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + SipTrunksClient._get_universe_domain(None, None) + == SipTrunksClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + SipTrunksClient._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 = SipTrunksClient(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 = SipTrunksClient(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", + [ + (SipTrunksClient, "grpc"), + (SipTrunksAsyncClient, "grpc_asyncio"), + (SipTrunksClient, "rest"), + ], +) +def test_sip_trunks_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 == ( + "dialogflow.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://dialogflow.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.SipTrunksGrpcTransport, "grpc"), + (transports.SipTrunksGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.SipTrunksRestTransport, "rest"), + ], +) +def test_sip_trunks_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", + [ + (SipTrunksClient, "grpc"), + (SipTrunksAsyncClient, "grpc_asyncio"), + (SipTrunksClient, "rest"), + ], +) +def test_sip_trunks_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 == ( + "dialogflow.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://dialogflow.googleapis.com" + ) + + +def test_sip_trunks_client_get_transport_class(): + transport = SipTrunksClient.get_transport_class() + available_transports = [ + transports.SipTrunksGrpcTransport, + transports.SipTrunksRestTransport, + ] + assert transport in available_transports + + transport = SipTrunksClient.get_transport_class("grpc") + assert transport == transports.SipTrunksGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (SipTrunksClient, transports.SipTrunksGrpcTransport, "grpc"), + ( + SipTrunksAsyncClient, + transports.SipTrunksGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (SipTrunksClient, transports.SipTrunksRestTransport, "rest"), + ], +) +@mock.patch.object( + SipTrunksClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SipTrunksClient), +) +@mock.patch.object( + SipTrunksAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SipTrunksAsyncClient), +) +def test_sip_trunks_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(SipTrunksClient, "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(SipTrunksClient, "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", + [ + (SipTrunksClient, transports.SipTrunksGrpcTransport, "grpc", "true"), + ( + SipTrunksAsyncClient, + transports.SipTrunksGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (SipTrunksClient, transports.SipTrunksGrpcTransport, "grpc", "false"), + ( + SipTrunksAsyncClient, + transports.SipTrunksGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + (SipTrunksClient, transports.SipTrunksRestTransport, "rest", "true"), + (SipTrunksClient, transports.SipTrunksRestTransport, "rest", "false"), + ], +) +@mock.patch.object( + SipTrunksClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SipTrunksClient), +) +@mock.patch.object( + SipTrunksAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SipTrunksAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_sip_trunks_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", [SipTrunksClient, SipTrunksAsyncClient]) +@mock.patch.object( + SipTrunksClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SipTrunksClient) +) +@mock.patch.object( + SipTrunksAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(SipTrunksAsyncClient), +) +def test_sip_trunks_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", [SipTrunksClient, SipTrunksAsyncClient]) +@mock.patch.object( + SipTrunksClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SipTrunksClient), +) +@mock.patch.object( + SipTrunksAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(SipTrunksAsyncClient), +) +def test_sip_trunks_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = SipTrunksClient._DEFAULT_UNIVERSE + default_endpoint = SipTrunksClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = SipTrunksClient._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", + [ + (SipTrunksClient, transports.SipTrunksGrpcTransport, "grpc"), + ( + SipTrunksAsyncClient, + transports.SipTrunksGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (SipTrunksClient, transports.SipTrunksRestTransport, "rest"), + ], +) +def test_sip_trunks_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", + [ + (SipTrunksClient, transports.SipTrunksGrpcTransport, "grpc", grpc_helpers), + ( + SipTrunksAsyncClient, + transports.SipTrunksGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + (SipTrunksClient, transports.SipTrunksRestTransport, "rest", None), + ], +) +def test_sip_trunks_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_sip_trunks_client_client_options_from_dict(): + with mock.patch( + "google.cloud.dialogflow_v2.services.sip_trunks.transports.SipTrunksGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = SipTrunksClient(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", + [ + (SipTrunksClient, transports.SipTrunksGrpcTransport, "grpc", grpc_helpers), + ( + SipTrunksAsyncClient, + transports.SipTrunksGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_sip_trunks_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( + "dialogflow.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + scopes=None, + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gcd_sip_trunk.CreateSipTrunkRequest, + dict, + ], +) +def test_create_sip_trunk(request_type, transport: str = "grpc"): + client = SipTrunksClient( + 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_sip_trunk), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_sip_trunk.SipTrunk( + name="name_value", + expected_hostname=["expected_hostname_value"], + display_name="display_name_value", + ) + response = client.create_sip_trunk(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcd_sip_trunk.CreateSipTrunkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_sip_trunk.SipTrunk) + assert response.name == "name_value" + assert response.expected_hostname == ["expected_hostname_value"] + assert response.display_name == "display_name_value" + + +def test_create_sip_trunk_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 = SipTrunksClient( + 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 = gcd_sip_trunk.CreateSipTrunkRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_sip_trunk), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_sip_trunk(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_sip_trunk.CreateSipTrunkRequest( + parent="parent_value", + ) + + +def test_create_sip_trunk_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 = SipTrunksClient( + 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_sip_trunk 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_sip_trunk + ] = mock_rpc + request = {} + client.create_sip_trunk(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_sip_trunk(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_sip_trunk_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 = SipTrunksAsyncClient( + 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_sip_trunk + 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_sip_trunk + ] = mock_rpc + + request = {} + await client.create_sip_trunk(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_sip_trunk(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_sip_trunk_async( + transport: str = "grpc_asyncio", request_type=gcd_sip_trunk.CreateSipTrunkRequest +): + client = SipTrunksAsyncClient( + 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_sip_trunk), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_sip_trunk.SipTrunk( + name="name_value", + expected_hostname=["expected_hostname_value"], + display_name="display_name_value", + ) + ) + response = await client.create_sip_trunk(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcd_sip_trunk.CreateSipTrunkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_sip_trunk.SipTrunk) + assert response.name == "name_value" + assert response.expected_hostname == ["expected_hostname_value"] + assert response.display_name == "display_name_value" + + +@pytest.mark.asyncio +async def test_create_sip_trunk_async_from_dict(): + await test_create_sip_trunk_async(request_type=dict) + + +def test_create_sip_trunk_field_headers(): + client = SipTrunksClient( + 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 = gcd_sip_trunk.CreateSipTrunkRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_sip_trunk), "__call__") as call: + call.return_value = gcd_sip_trunk.SipTrunk() + client.create_sip_trunk(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_sip_trunk_field_headers_async(): + client = SipTrunksAsyncClient( + 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 = gcd_sip_trunk.CreateSipTrunkRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_sip_trunk), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_sip_trunk.SipTrunk() + ) + await client.create_sip_trunk(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_sip_trunk_flattened(): + client = SipTrunksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_sip_trunk), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_sip_trunk.SipTrunk() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_sip_trunk( + parent="parent_value", + sip_trunk=gcd_sip_trunk.SipTrunk(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].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].sip_trunk + mock_val = gcd_sip_trunk.SipTrunk(name="name_value") + assert arg == mock_val + + +def test_create_sip_trunk_flattened_error(): + client = SipTrunksClient( + 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_sip_trunk( + gcd_sip_trunk.CreateSipTrunkRequest(), + parent="parent_value", + sip_trunk=gcd_sip_trunk.SipTrunk(name="name_value"), + ) + + +@pytest.mark.asyncio +async def test_create_sip_trunk_flattened_async(): + client = SipTrunksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_sip_trunk), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_sip_trunk.SipTrunk() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_sip_trunk.SipTrunk() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_sip_trunk( + parent="parent_value", + sip_trunk=gcd_sip_trunk.SipTrunk(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].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].sip_trunk + mock_val = gcd_sip_trunk.SipTrunk(name="name_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_sip_trunk_flattened_error_async(): + client = SipTrunksAsyncClient( + 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_sip_trunk( + gcd_sip_trunk.CreateSipTrunkRequest(), + parent="parent_value", + sip_trunk=gcd_sip_trunk.SipTrunk(name="name_value"), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + sip_trunk.DeleteSipTrunkRequest, + dict, + ], +) +def test_delete_sip_trunk(request_type, transport: str = "grpc"): + client = SipTrunksClient( + 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_sip_trunk), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_sip_trunk(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = sip_trunk.DeleteSipTrunkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_sip_trunk_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 = SipTrunksClient( + 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 = sip_trunk.DeleteSipTrunkRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_sip_trunk), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_sip_trunk(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sip_trunk.DeleteSipTrunkRequest( + name="name_value", + ) + + +def test_delete_sip_trunk_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 = SipTrunksClient( + 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_sip_trunk 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_sip_trunk + ] = mock_rpc + request = {} + client.delete_sip_trunk(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_sip_trunk(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_sip_trunk_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 = SipTrunksAsyncClient( + 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_sip_trunk + 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_sip_trunk + ] = mock_rpc + + request = {} + await client.delete_sip_trunk(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.delete_sip_trunk(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_sip_trunk_async( + transport: str = "grpc_asyncio", request_type=sip_trunk.DeleteSipTrunkRequest +): + client = SipTrunksAsyncClient( + 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_sip_trunk), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_sip_trunk(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = sip_trunk.DeleteSipTrunkRequest() + 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_sip_trunk_async_from_dict(): + await test_delete_sip_trunk_async(request_type=dict) + + +def test_delete_sip_trunk_field_headers(): + client = SipTrunksClient( + 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 = sip_trunk.DeleteSipTrunkRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_sip_trunk), "__call__") as call: + call.return_value = None + client.delete_sip_trunk(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_sip_trunk_field_headers_async(): + client = SipTrunksAsyncClient( + 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 = sip_trunk.DeleteSipTrunkRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_sip_trunk), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_sip_trunk(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_sip_trunk_flattened(): + client = SipTrunksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_sip_trunk), "__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_sip_trunk( + 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_sip_trunk_flattened_error(): + client = SipTrunksClient( + 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_sip_trunk( + sip_trunk.DeleteSipTrunkRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_sip_trunk_flattened_async(): + client = SipTrunksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_sip_trunk), "__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_sip_trunk( + 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_sip_trunk_flattened_error_async(): + client = SipTrunksAsyncClient( + 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_sip_trunk( + sip_trunk.DeleteSipTrunkRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + sip_trunk.ListSipTrunksRequest, + dict, + ], +) +def test_list_sip_trunks(request_type, transport: str = "grpc"): + client = SipTrunksClient( + 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_sip_trunks), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = sip_trunk.ListSipTrunksResponse( + next_page_token="next_page_token_value", + ) + response = client.list_sip_trunks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = sip_trunk.ListSipTrunksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSipTrunksPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_sip_trunks_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 = SipTrunksClient( + 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 = sip_trunk.ListSipTrunksRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_sip_trunks), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_sip_trunks(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sip_trunk.ListSipTrunksRequest( + parent="parent_value", + page_token="page_token_value", + ) + + +def test_list_sip_trunks_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 = SipTrunksClient( + 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_sip_trunks 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_sip_trunks] = mock_rpc + request = {} + client.list_sip_trunks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_sip_trunks(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_sip_trunks_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 = SipTrunksAsyncClient( + 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_sip_trunks + 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_sip_trunks + ] = mock_rpc + + request = {} + await client.list_sip_trunks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_sip_trunks(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_sip_trunks_async( + transport: str = "grpc_asyncio", request_type=sip_trunk.ListSipTrunksRequest +): + client = SipTrunksAsyncClient( + 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_sip_trunks), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sip_trunk.ListSipTrunksResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_sip_trunks(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = sip_trunk.ListSipTrunksRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSipTrunksAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_sip_trunks_async_from_dict(): + await test_list_sip_trunks_async(request_type=dict) + + +def test_list_sip_trunks_field_headers(): + client = SipTrunksClient( + 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 = sip_trunk.ListSipTrunksRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_sip_trunks), "__call__") as call: + call.return_value = sip_trunk.ListSipTrunksResponse() + client.list_sip_trunks(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_sip_trunks_field_headers_async(): + client = SipTrunksAsyncClient( + 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 = sip_trunk.ListSipTrunksRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_sip_trunks), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sip_trunk.ListSipTrunksResponse() + ) + await client.list_sip_trunks(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_sip_trunks_flattened(): + client = SipTrunksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_sip_trunks), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = sip_trunk.ListSipTrunksResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_sip_trunks( + 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_sip_trunks_flattened_error(): + client = SipTrunksClient( + 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_sip_trunks( + sip_trunk.ListSipTrunksRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_sip_trunks_flattened_async(): + client = SipTrunksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_sip_trunks), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = sip_trunk.ListSipTrunksResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sip_trunk.ListSipTrunksResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_sip_trunks( + 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_sip_trunks_flattened_error_async(): + client = SipTrunksAsyncClient( + 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_sip_trunks( + sip_trunk.ListSipTrunksRequest(), + parent="parent_value", + ) + + +def test_list_sip_trunks_pager(transport_name: str = "grpc"): + client = SipTrunksClient( + 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_sip_trunks), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + sip_trunk.ListSipTrunksResponse( + sip_trunks=[ + sip_trunk.SipTrunk(), + sip_trunk.SipTrunk(), + sip_trunk.SipTrunk(), + ], + next_page_token="abc", + ), + sip_trunk.ListSipTrunksResponse( + sip_trunks=[], + next_page_token="def", + ), + sip_trunk.ListSipTrunksResponse( + sip_trunks=[ + sip_trunk.SipTrunk(), + ], + next_page_token="ghi", + ), + sip_trunk.ListSipTrunksResponse( + sip_trunks=[ + sip_trunk.SipTrunk(), + sip_trunk.SipTrunk(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_sip_trunks(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, sip_trunk.SipTrunk) for i in results) + + +def test_list_sip_trunks_pages(transport_name: str = "grpc"): + client = SipTrunksClient( + 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_sip_trunks), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + sip_trunk.ListSipTrunksResponse( + sip_trunks=[ + sip_trunk.SipTrunk(), + sip_trunk.SipTrunk(), + sip_trunk.SipTrunk(), + ], + next_page_token="abc", + ), + sip_trunk.ListSipTrunksResponse( + sip_trunks=[], + next_page_token="def", + ), + sip_trunk.ListSipTrunksResponse( + sip_trunks=[ + sip_trunk.SipTrunk(), + ], + next_page_token="ghi", + ), + sip_trunk.ListSipTrunksResponse( + sip_trunks=[ + sip_trunk.SipTrunk(), + sip_trunk.SipTrunk(), + ], + ), + RuntimeError, + ) + pages = list(client.list_sip_trunks(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_sip_trunks_async_pager(): + client = SipTrunksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sip_trunks), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + sip_trunk.ListSipTrunksResponse( + sip_trunks=[ + sip_trunk.SipTrunk(), + sip_trunk.SipTrunk(), + sip_trunk.SipTrunk(), + ], + next_page_token="abc", + ), + sip_trunk.ListSipTrunksResponse( + sip_trunks=[], + next_page_token="def", + ), + sip_trunk.ListSipTrunksResponse( + sip_trunks=[ + sip_trunk.SipTrunk(), + ], + next_page_token="ghi", + ), + sip_trunk.ListSipTrunksResponse( + sip_trunks=[ + sip_trunk.SipTrunk(), + sip_trunk.SipTrunk(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_sip_trunks( + 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, sip_trunk.SipTrunk) for i in responses) + + +@pytest.mark.asyncio +async def test_list_sip_trunks_async_pages(): + client = SipTrunksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_sip_trunks), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + sip_trunk.ListSipTrunksResponse( + sip_trunks=[ + sip_trunk.SipTrunk(), + sip_trunk.SipTrunk(), + sip_trunk.SipTrunk(), + ], + next_page_token="abc", + ), + sip_trunk.ListSipTrunksResponse( + sip_trunks=[], + next_page_token="def", + ), + sip_trunk.ListSipTrunksResponse( + sip_trunks=[ + sip_trunk.SipTrunk(), + ], + next_page_token="ghi", + ), + sip_trunk.ListSipTrunksResponse( + sip_trunks=[ + sip_trunk.SipTrunk(), + sip_trunk.SipTrunk(), + ], + ), + 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_sip_trunks(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", + [ + sip_trunk.GetSipTrunkRequest, + dict, + ], +) +def test_get_sip_trunk(request_type, transport: str = "grpc"): + client = SipTrunksClient( + 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_sip_trunk), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = sip_trunk.SipTrunk( + name="name_value", + expected_hostname=["expected_hostname_value"], + display_name="display_name_value", + ) + response = client.get_sip_trunk(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = sip_trunk.GetSipTrunkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, sip_trunk.SipTrunk) + assert response.name == "name_value" + assert response.expected_hostname == ["expected_hostname_value"] + assert response.display_name == "display_name_value" + + +def test_get_sip_trunk_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 = SipTrunksClient( + 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 = sip_trunk.GetSipTrunkRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_sip_trunk), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_sip_trunk(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == sip_trunk.GetSipTrunkRequest( + name="name_value", + ) + + +def test_get_sip_trunk_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 = SipTrunksClient( + 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_sip_trunk 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_sip_trunk] = mock_rpc + request = {} + client.get_sip_trunk(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_sip_trunk(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_sip_trunk_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 = SipTrunksAsyncClient( + 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_sip_trunk + 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_sip_trunk + ] = mock_rpc + + request = {} + await client.get_sip_trunk(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_sip_trunk(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_sip_trunk_async( + transport: str = "grpc_asyncio", request_type=sip_trunk.GetSipTrunkRequest +): + client = SipTrunksAsyncClient( + 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_sip_trunk), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sip_trunk.SipTrunk( + name="name_value", + expected_hostname=["expected_hostname_value"], + display_name="display_name_value", + ) + ) + response = await client.get_sip_trunk(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = sip_trunk.GetSipTrunkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, sip_trunk.SipTrunk) + assert response.name == "name_value" + assert response.expected_hostname == ["expected_hostname_value"] + assert response.display_name == "display_name_value" + + +@pytest.mark.asyncio +async def test_get_sip_trunk_async_from_dict(): + await test_get_sip_trunk_async(request_type=dict) + + +def test_get_sip_trunk_field_headers(): + client = SipTrunksClient( + 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 = sip_trunk.GetSipTrunkRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_sip_trunk), "__call__") as call: + call.return_value = sip_trunk.SipTrunk() + client.get_sip_trunk(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_sip_trunk_field_headers_async(): + client = SipTrunksAsyncClient( + 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 = sip_trunk.GetSipTrunkRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_sip_trunk), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(sip_trunk.SipTrunk()) + await client.get_sip_trunk(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_sip_trunk_flattened(): + client = SipTrunksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_sip_trunk), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = sip_trunk.SipTrunk() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_sip_trunk( + 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_sip_trunk_flattened_error(): + client = SipTrunksClient( + 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_sip_trunk( + sip_trunk.GetSipTrunkRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_sip_trunk_flattened_async(): + client = SipTrunksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_sip_trunk), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = sip_trunk.SipTrunk() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(sip_trunk.SipTrunk()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_sip_trunk( + 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_sip_trunk_flattened_error_async(): + client = SipTrunksAsyncClient( + 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_sip_trunk( + sip_trunk.GetSipTrunkRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gcd_sip_trunk.UpdateSipTrunkRequest, + dict, + ], +) +def test_update_sip_trunk(request_type, transport: str = "grpc"): + client = SipTrunksClient( + 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_sip_trunk), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_sip_trunk.SipTrunk( + name="name_value", + expected_hostname=["expected_hostname_value"], + display_name="display_name_value", + ) + response = client.update_sip_trunk(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcd_sip_trunk.UpdateSipTrunkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_sip_trunk.SipTrunk) + assert response.name == "name_value" + assert response.expected_hostname == ["expected_hostname_value"] + assert response.display_name == "display_name_value" + + +def test_update_sip_trunk_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 = SipTrunksClient( + 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 = gcd_sip_trunk.UpdateSipTrunkRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_sip_trunk), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_sip_trunk(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == gcd_sip_trunk.UpdateSipTrunkRequest() + + +def test_update_sip_trunk_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 = SipTrunksClient( + 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_sip_trunk 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_sip_trunk + ] = mock_rpc + request = {} + client.update_sip_trunk(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_sip_trunk(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_sip_trunk_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 = SipTrunksAsyncClient( + 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_sip_trunk + 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_sip_trunk + ] = mock_rpc + + request = {} + await client.update_sip_trunk(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_sip_trunk(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_sip_trunk_async( + transport: str = "grpc_asyncio", request_type=gcd_sip_trunk.UpdateSipTrunkRequest +): + client = SipTrunksAsyncClient( + 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_sip_trunk), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_sip_trunk.SipTrunk( + name="name_value", + expected_hostname=["expected_hostname_value"], + display_name="display_name_value", + ) + ) + response = await client.update_sip_trunk(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcd_sip_trunk.UpdateSipTrunkRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_sip_trunk.SipTrunk) + assert response.name == "name_value" + assert response.expected_hostname == ["expected_hostname_value"] + assert response.display_name == "display_name_value" + + +@pytest.mark.asyncio +async def test_update_sip_trunk_async_from_dict(): + await test_update_sip_trunk_async(request_type=dict) + + +def test_update_sip_trunk_field_headers(): + client = SipTrunksClient( + 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 = gcd_sip_trunk.UpdateSipTrunkRequest() + + request.sip_trunk.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_sip_trunk), "__call__") as call: + call.return_value = gcd_sip_trunk.SipTrunk() + client.update_sip_trunk(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", + "sip_trunk.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_sip_trunk_field_headers_async(): + client = SipTrunksAsyncClient( + 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 = gcd_sip_trunk.UpdateSipTrunkRequest() + + request.sip_trunk.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_sip_trunk), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_sip_trunk.SipTrunk() + ) + await client.update_sip_trunk(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", + "sip_trunk.name=name_value", + ) in kw["metadata"] + + +def test_update_sip_trunk_flattened(): + client = SipTrunksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_sip_trunk), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_sip_trunk.SipTrunk() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_sip_trunk( + sip_trunk=gcd_sip_trunk.SipTrunk(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].sip_trunk + mock_val = gcd_sip_trunk.SipTrunk(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_sip_trunk_flattened_error(): + client = SipTrunksClient( + 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_sip_trunk( + gcd_sip_trunk.UpdateSipTrunkRequest(), + sip_trunk=gcd_sip_trunk.SipTrunk(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_sip_trunk_flattened_async(): + client = SipTrunksAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_sip_trunk), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcd_sip_trunk.SipTrunk() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_sip_trunk.SipTrunk() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_sip_trunk( + sip_trunk=gcd_sip_trunk.SipTrunk(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].sip_trunk + mock_val = gcd_sip_trunk.SipTrunk(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_sip_trunk_flattened_error_async(): + client = SipTrunksAsyncClient( + 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_sip_trunk( + gcd_sip_trunk.UpdateSipTrunkRequest(), + sip_trunk=gcd_sip_trunk.SipTrunk(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_create_sip_trunk_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 = SipTrunksClient( + 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_sip_trunk 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_sip_trunk + ] = mock_rpc + + request = {} + client.create_sip_trunk(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_sip_trunk(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_sip_trunk_rest_required_fields( + request_type=gcd_sip_trunk.CreateSipTrunkRequest, +): + transport_class = transports.SipTrunksRestTransport + + 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_sip_trunk._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_sip_trunk._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 = SipTrunksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcd_sip_trunk.SipTrunk() + # 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 = gcd_sip_trunk.SipTrunk.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_sip_trunk(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_sip_trunk_rest_unset_required_fields(): + transport = transports.SipTrunksRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_sip_trunk._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "sipTrunk", + ) + ) + ) + + +def test_create_sip_trunk_rest_flattened(): + client = SipTrunksClient( + 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 = gcd_sip_trunk.SipTrunk() + + # 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", + sip_trunk=gcd_sip_trunk.SipTrunk(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 = gcd_sip_trunk.SipTrunk.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_sip_trunk(**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/v2/{parent=projects/*/locations/*}/sipTrunks" % client.transport._host, + args[1], + ) + + +def test_create_sip_trunk_rest_flattened_error(transport: str = "rest"): + client = SipTrunksClient( + 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_sip_trunk( + gcd_sip_trunk.CreateSipTrunkRequest(), + parent="parent_value", + sip_trunk=gcd_sip_trunk.SipTrunk(name="name_value"), + ) + + +def test_delete_sip_trunk_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 = SipTrunksClient( + 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_sip_trunk 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_sip_trunk + ] = mock_rpc + + request = {} + client.delete_sip_trunk(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_sip_trunk(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_sip_trunk_rest_required_fields( + request_type=sip_trunk.DeleteSipTrunkRequest, +): + transport_class = transports.SipTrunksRestTransport + + 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_sip_trunk._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_sip_trunk._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 = SipTrunksClient( + 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_sip_trunk(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_sip_trunk_rest_unset_required_fields(): + transport = transports.SipTrunksRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_sip_trunk._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_delete_sip_trunk_rest_flattened(): + client = SipTrunksClient( + 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/sipTrunks/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 = "" + response_value._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_sip_trunk(**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/v2/{name=projects/*/locations/*/sipTrunks/*}" % client.transport._host, + args[1], + ) + + +def test_delete_sip_trunk_rest_flattened_error(transport: str = "rest"): + client = SipTrunksClient( + 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_sip_trunk( + sip_trunk.DeleteSipTrunkRequest(), + name="name_value", + ) + + +def test_list_sip_trunks_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 = SipTrunksClient( + 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_sip_trunks 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_sip_trunks] = mock_rpc + + request = {} + client.list_sip_trunks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_sip_trunks(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_sip_trunks_rest_required_fields( + request_type=sip_trunk.ListSipTrunksRequest, +): + transport_class = transports.SipTrunksRestTransport + + 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_sip_trunks._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_sip_trunks._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "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 = SipTrunksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = sip_trunk.ListSipTrunksResponse() + # 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 = sip_trunk.ListSipTrunksResponse.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_sip_trunks(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_sip_trunks_rest_unset_required_fields(): + transport = transports.SipTrunksRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_sip_trunks._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_sip_trunks_rest_flattened(): + client = SipTrunksClient( + 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 = sip_trunk.ListSipTrunksResponse() + + # 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 = sip_trunk.ListSipTrunksResponse.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_sip_trunks(**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/v2/{parent=projects/*/locations/*}/sipTrunks" % client.transport._host, + args[1], + ) + + +def test_list_sip_trunks_rest_flattened_error(transport: str = "rest"): + client = SipTrunksClient( + 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_sip_trunks( + sip_trunk.ListSipTrunksRequest(), + parent="parent_value", + ) + + +def test_list_sip_trunks_rest_pager(transport: str = "rest"): + client = SipTrunksClient( + 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 = ( + sip_trunk.ListSipTrunksResponse( + sip_trunks=[ + sip_trunk.SipTrunk(), + sip_trunk.SipTrunk(), + sip_trunk.SipTrunk(), + ], + next_page_token="abc", + ), + sip_trunk.ListSipTrunksResponse( + sip_trunks=[], + next_page_token="def", + ), + sip_trunk.ListSipTrunksResponse( + sip_trunks=[ + sip_trunk.SipTrunk(), + ], + next_page_token="ghi", + ), + sip_trunk.ListSipTrunksResponse( + sip_trunks=[ + sip_trunk.SipTrunk(), + sip_trunk.SipTrunk(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(sip_trunk.ListSipTrunksResponse.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_sip_trunks(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, sip_trunk.SipTrunk) for i in results) + + pages = list(client.list_sip_trunks(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_sip_trunk_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 = SipTrunksClient( + 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_sip_trunk 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_sip_trunk] = mock_rpc + + request = {} + client.get_sip_trunk(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_sip_trunk(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_sip_trunk_rest_required_fields(request_type=sip_trunk.GetSipTrunkRequest): + transport_class = transports.SipTrunksRestTransport + + 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_sip_trunk._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_sip_trunk._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 = SipTrunksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = sip_trunk.SipTrunk() + # 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 = sip_trunk.SipTrunk.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_sip_trunk(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_sip_trunk_rest_unset_required_fields(): + transport = transports.SipTrunksRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_sip_trunk._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_sip_trunk_rest_flattened(): + client = SipTrunksClient( + 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 = sip_trunk.SipTrunk() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/sipTrunks/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 = sip_trunk.SipTrunk.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_sip_trunk(**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/v2/{name=projects/*/locations/*/sipTrunks/*}" % client.transport._host, + args[1], + ) + + +def test_get_sip_trunk_rest_flattened_error(transport: str = "rest"): + client = SipTrunksClient( + 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_sip_trunk( + sip_trunk.GetSipTrunkRequest(), + name="name_value", + ) + + +def test_update_sip_trunk_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 = SipTrunksClient( + 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_sip_trunk 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_sip_trunk + ] = mock_rpc + + request = {} + client.update_sip_trunk(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_sip_trunk(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_sip_trunk_rest_required_fields( + request_type=gcd_sip_trunk.UpdateSipTrunkRequest, +): + transport_class = transports.SipTrunksRestTransport + + 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_sip_trunk._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_sip_trunk._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 = SipTrunksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcd_sip_trunk.SipTrunk() + # 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 = gcd_sip_trunk.SipTrunk.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_sip_trunk(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_sip_trunk_rest_unset_required_fields(): + transport = transports.SipTrunksRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_sip_trunk._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("sipTrunk",))) + + +def test_update_sip_trunk_rest_flattened(): + client = SipTrunksClient( + 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 = gcd_sip_trunk.SipTrunk() + + # get arguments that satisfy an http rule for this method + sample_request = { + "sip_trunk": { + "name": "projects/sample1/locations/sample2/sipTrunks/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + sip_trunk=gcd_sip_trunk.SipTrunk(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 = gcd_sip_trunk.SipTrunk.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_sip_trunk(**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/v2/{sip_trunk.name=projects/*/locations/*/sipTrunks/*}" + % client.transport._host, + args[1], + ) + + +def test_update_sip_trunk_rest_flattened_error(transport: str = "rest"): + client = SipTrunksClient( + 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_sip_trunk( + gcd_sip_trunk.UpdateSipTrunkRequest(), + sip_trunk=gcd_sip_trunk.SipTrunk(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.SipTrunksGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SipTrunksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.SipTrunksGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SipTrunksClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.SipTrunksGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = SipTrunksClient( + 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 = SipTrunksClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.SipTrunksGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = SipTrunksClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.SipTrunksGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = SipTrunksClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.SipTrunksGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.SipTrunksGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SipTrunksGrpcTransport, + transports.SipTrunksGrpcAsyncIOTransport, + transports.SipTrunksRestTransport, + ], +) +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 = SipTrunksClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = SipTrunksClient( + 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_create_sip_trunk_empty_call_grpc(): + client = SipTrunksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_sip_trunk), "__call__") as call: + call.return_value = gcd_sip_trunk.SipTrunk() + client.create_sip_trunk(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcd_sip_trunk.CreateSipTrunkRequest() + + 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_sip_trunk_empty_call_grpc(): + client = SipTrunksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_sip_trunk), "__call__") as call: + call.return_value = None + client.delete_sip_trunk(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sip_trunk.DeleteSipTrunkRequest() + + 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_sip_trunks_empty_call_grpc(): + client = SipTrunksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_sip_trunks), "__call__") as call: + call.return_value = sip_trunk.ListSipTrunksResponse() + client.list_sip_trunks(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sip_trunk.ListSipTrunksRequest() + + 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_sip_trunk_empty_call_grpc(): + client = SipTrunksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_sip_trunk), "__call__") as call: + call.return_value = sip_trunk.SipTrunk() + client.get_sip_trunk(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sip_trunk.GetSipTrunkRequest() + + 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_sip_trunk_empty_call_grpc(): + client = SipTrunksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_sip_trunk), "__call__") as call: + call.return_value = gcd_sip_trunk.SipTrunk() + client.update_sip_trunk(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcd_sip_trunk.UpdateSipTrunkRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = SipTrunksAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = SipTrunksAsyncClient( + 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_create_sip_trunk_empty_call_grpc_asyncio(): + client = SipTrunksAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_sip_trunk), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_sip_trunk.SipTrunk( + name="name_value", + expected_hostname=["expected_hostname_value"], + display_name="display_name_value", + ) + ) + await client.create_sip_trunk(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcd_sip_trunk.CreateSipTrunkRequest() + + 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_sip_trunk_empty_call_grpc_asyncio(): + client = SipTrunksAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_sip_trunk), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_sip_trunk(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sip_trunk.DeleteSipTrunkRequest() + + 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_sip_trunks_empty_call_grpc_asyncio(): + client = SipTrunksAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_sip_trunks), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sip_trunk.ListSipTrunksResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_sip_trunks(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sip_trunk.ListSipTrunksRequest() + + 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_sip_trunk_empty_call_grpc_asyncio(): + client = SipTrunksAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_sip_trunk), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + sip_trunk.SipTrunk( + name="name_value", + expected_hostname=["expected_hostname_value"], + display_name="display_name_value", + ) + ) + await client.get_sip_trunk(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sip_trunk.GetSipTrunkRequest() + + 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_sip_trunk_empty_call_grpc_asyncio(): + client = SipTrunksAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_sip_trunk), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcd_sip_trunk.SipTrunk( + name="name_value", + expected_hostname=["expected_hostname_value"], + display_name="display_name_value", + ) + ) + await client.update_sip_trunk(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcd_sip_trunk.UpdateSipTrunkRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = SipTrunksClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_sip_trunk_rest_bad_request( + request_type=gcd_sip_trunk.CreateSipTrunkRequest, +): + client = SipTrunksClient( + 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_sip_trunk(request) + + +@pytest.mark.parametrize( + "request_type", + [ + gcd_sip_trunk.CreateSipTrunkRequest, + dict, + ], +) +def test_create_sip_trunk_rest_call_success(request_type): + client = SipTrunksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["sip_trunk"] = { + "name": "name_value", + "expected_hostname": ["expected_hostname_value1", "expected_hostname_value2"], + "connections": [ + { + "connection_id": "connection_id_value", + "state": 1, + "update_time": {"seconds": 751, "nanos": 543}, + "error_details": { + "certificate_state": 1, + "error_message": "error_message_value", + }, + } + ], + "display_name": "display_name_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 = gcd_sip_trunk.CreateSipTrunkRequest.meta.fields["sip_trunk"] + + 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["sip_trunk"].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["sip_trunk"][field])): + del request_init["sip_trunk"][field][i][subfield] + else: + del request_init["sip_trunk"][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 = gcd_sip_trunk.SipTrunk( + name="name_value", + expected_hostname=["expected_hostname_value"], + display_name="display_name_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 = gcd_sip_trunk.SipTrunk.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_sip_trunk(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_sip_trunk.SipTrunk) + assert response.name == "name_value" + assert response.expected_hostname == ["expected_hostname_value"] + assert response.display_name == "display_name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_sip_trunk_rest_interceptors(null_interceptor): + transport = transports.SipTrunksRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SipTrunksRestInterceptor(), + ) + client = SipTrunksClient(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.SipTrunksRestInterceptor, "post_create_sip_trunk" + ) as post, mock.patch.object( + transports.SipTrunksRestInterceptor, "post_create_sip_trunk_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.SipTrunksRestInterceptor, "pre_create_sip_trunk" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcd_sip_trunk.CreateSipTrunkRequest.pb( + gcd_sip_trunk.CreateSipTrunkRequest() + ) + 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 = gcd_sip_trunk.SipTrunk.to_json(gcd_sip_trunk.SipTrunk()) + req.return_value.content = return_value + + request = gcd_sip_trunk.CreateSipTrunkRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcd_sip_trunk.SipTrunk() + post_with_metadata.return_value = gcd_sip_trunk.SipTrunk(), metadata + + client.create_sip_trunk( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_sip_trunk_rest_bad_request( + request_type=sip_trunk.DeleteSipTrunkRequest, +): + client = SipTrunksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/sipTrunks/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_sip_trunk(request) + + +@pytest.mark.parametrize( + "request_type", + [ + sip_trunk.DeleteSipTrunkRequest, + dict, + ], +) +def test_delete_sip_trunk_rest_call_success(request_type): + client = SipTrunksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/sipTrunks/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 = 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_sip_trunk(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_sip_trunk_rest_interceptors(null_interceptor): + transport = transports.SipTrunksRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SipTrunksRestInterceptor(), + ) + client = SipTrunksClient(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.SipTrunksRestInterceptor, "pre_delete_sip_trunk" + ) as pre: + pre.assert_not_called() + pb_message = sip_trunk.DeleteSipTrunkRequest.pb( + sip_trunk.DeleteSipTrunkRequest() + ) + 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 = sip_trunk.DeleteSipTrunkRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_sip_trunk( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_list_sip_trunks_rest_bad_request(request_type=sip_trunk.ListSipTrunksRequest): + client = SipTrunksClient( + 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_sip_trunks(request) + + +@pytest.mark.parametrize( + "request_type", + [ + sip_trunk.ListSipTrunksRequest, + dict, + ], +) +def test_list_sip_trunks_rest_call_success(request_type): + client = SipTrunksClient( + 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 = sip_trunk.ListSipTrunksResponse( + 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 = sip_trunk.ListSipTrunksResponse.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_sip_trunks(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSipTrunksPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_sip_trunks_rest_interceptors(null_interceptor): + transport = transports.SipTrunksRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SipTrunksRestInterceptor(), + ) + client = SipTrunksClient(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.SipTrunksRestInterceptor, "post_list_sip_trunks" + ) as post, mock.patch.object( + transports.SipTrunksRestInterceptor, "post_list_sip_trunks_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.SipTrunksRestInterceptor, "pre_list_sip_trunks" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = sip_trunk.ListSipTrunksRequest.pb(sip_trunk.ListSipTrunksRequest()) + 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 = sip_trunk.ListSipTrunksResponse.to_json( + sip_trunk.ListSipTrunksResponse() + ) + req.return_value.content = return_value + + request = sip_trunk.ListSipTrunksRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = sip_trunk.ListSipTrunksResponse() + post_with_metadata.return_value = sip_trunk.ListSipTrunksResponse(), metadata + + client.list_sip_trunks( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_sip_trunk_rest_bad_request(request_type=sip_trunk.GetSipTrunkRequest): + client = SipTrunksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/sipTrunks/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_sip_trunk(request) + + +@pytest.mark.parametrize( + "request_type", + [ + sip_trunk.GetSipTrunkRequest, + dict, + ], +) +def test_get_sip_trunk_rest_call_success(request_type): + client = SipTrunksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/sipTrunks/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 = sip_trunk.SipTrunk( + name="name_value", + expected_hostname=["expected_hostname_value"], + display_name="display_name_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 = sip_trunk.SipTrunk.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_sip_trunk(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, sip_trunk.SipTrunk) + assert response.name == "name_value" + assert response.expected_hostname == ["expected_hostname_value"] + assert response.display_name == "display_name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_sip_trunk_rest_interceptors(null_interceptor): + transport = transports.SipTrunksRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SipTrunksRestInterceptor(), + ) + client = SipTrunksClient(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.SipTrunksRestInterceptor, "post_get_sip_trunk" + ) as post, mock.patch.object( + transports.SipTrunksRestInterceptor, "post_get_sip_trunk_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.SipTrunksRestInterceptor, "pre_get_sip_trunk" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = sip_trunk.GetSipTrunkRequest.pb(sip_trunk.GetSipTrunkRequest()) + 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 = sip_trunk.SipTrunk.to_json(sip_trunk.SipTrunk()) + req.return_value.content = return_value + + request = sip_trunk.GetSipTrunkRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = sip_trunk.SipTrunk() + post_with_metadata.return_value = sip_trunk.SipTrunk(), metadata + + client.get_sip_trunk( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_sip_trunk_rest_bad_request( + request_type=gcd_sip_trunk.UpdateSipTrunkRequest, +): + client = SipTrunksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "sip_trunk": {"name": "projects/sample1/locations/sample2/sipTrunks/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_sip_trunk(request) + + +@pytest.mark.parametrize( + "request_type", + [ + gcd_sip_trunk.UpdateSipTrunkRequest, + dict, + ], +) +def test_update_sip_trunk_rest_call_success(request_type): + client = SipTrunksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "sip_trunk": {"name": "projects/sample1/locations/sample2/sipTrunks/sample3"} + } + request_init["sip_trunk"] = { + "name": "projects/sample1/locations/sample2/sipTrunks/sample3", + "expected_hostname": ["expected_hostname_value1", "expected_hostname_value2"], + "connections": [ + { + "connection_id": "connection_id_value", + "state": 1, + "update_time": {"seconds": 751, "nanos": 543}, + "error_details": { + "certificate_state": 1, + "error_message": "error_message_value", + }, + } + ], + "display_name": "display_name_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 = gcd_sip_trunk.UpdateSipTrunkRequest.meta.fields["sip_trunk"] + + 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["sip_trunk"].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["sip_trunk"][field])): + del request_init["sip_trunk"][field][i][subfield] + else: + del request_init["sip_trunk"][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 = gcd_sip_trunk.SipTrunk( + name="name_value", + expected_hostname=["expected_hostname_value"], + display_name="display_name_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 = gcd_sip_trunk.SipTrunk.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_sip_trunk(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_sip_trunk.SipTrunk) + assert response.name == "name_value" + assert response.expected_hostname == ["expected_hostname_value"] + assert response.display_name == "display_name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_sip_trunk_rest_interceptors(null_interceptor): + transport = transports.SipTrunksRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.SipTrunksRestInterceptor(), + ) + client = SipTrunksClient(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.SipTrunksRestInterceptor, "post_update_sip_trunk" + ) as post, mock.patch.object( + transports.SipTrunksRestInterceptor, "post_update_sip_trunk_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.SipTrunksRestInterceptor, "pre_update_sip_trunk" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcd_sip_trunk.UpdateSipTrunkRequest.pb( + gcd_sip_trunk.UpdateSipTrunkRequest() + ) + 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 = gcd_sip_trunk.SipTrunk.to_json(gcd_sip_trunk.SipTrunk()) + req.return_value.content = return_value + + request = gcd_sip_trunk.UpdateSipTrunkRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcd_sip_trunk.SipTrunk() + post_with_metadata.return_value = gcd_sip_trunk.SipTrunk(), metadata + + client.update_sip_trunk( + 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 = SipTrunksClient( + 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 = SipTrunksClient( + 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 = SipTrunksClient( + 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 = SipTrunksClient( + 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 = SipTrunksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/operations/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.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = SipTrunksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/operations/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 = 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_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = SipTrunksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/operations/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_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = SipTrunksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/operations/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.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 = SipTrunksClient( + 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_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = SipTrunksClient( + 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 = 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 = SipTrunksClient( + 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_create_sip_trunk_empty_call_rest(): + client = SipTrunksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_sip_trunk), "__call__") as call: + client.create_sip_trunk(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcd_sip_trunk.CreateSipTrunkRequest() + + 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_sip_trunk_empty_call_rest(): + client = SipTrunksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_sip_trunk), "__call__") as call: + client.delete_sip_trunk(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sip_trunk.DeleteSipTrunkRequest() + + 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_sip_trunks_empty_call_rest(): + client = SipTrunksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_sip_trunks), "__call__") as call: + client.list_sip_trunks(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sip_trunk.ListSipTrunksRequest() + + 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_sip_trunk_empty_call_rest(): + client = SipTrunksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_sip_trunk), "__call__") as call: + client.get_sip_trunk(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = sip_trunk.GetSipTrunkRequest() + + 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_sip_trunk_empty_call_rest(): + client = SipTrunksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_sip_trunk), "__call__") as call: + client.update_sip_trunk(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcd_sip_trunk.UpdateSipTrunkRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = SipTrunksClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.SipTrunksGrpcTransport, + ) + + +def test_sip_trunks_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.SipTrunksTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_sip_trunks_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.dialogflow_v2.services.sip_trunks.transports.SipTrunksTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.SipTrunksTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "create_sip_trunk", + "delete_sip_trunk", + "list_sip_trunks", + "get_sip_trunk", + "update_sip_trunk", + "get_location", + "list_locations", + "get_operation", + "cancel_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_sip_trunks_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.dialogflow_v2.services.sip_trunks.transports.SipTrunksTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SipTrunksTransport( + 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/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +def test_sip_trunks_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.dialogflow_v2.services.sip_trunks.transports.SipTrunksTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.SipTrunksTransport() + adc.assert_called_once() + + +def test_sip_trunks_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) + SipTrunksClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SipTrunksGrpcTransport, + transports.SipTrunksGrpcAsyncIOTransport, + ], +) +def test_sip_trunks_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/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.SipTrunksGrpcTransport, + transports.SipTrunksGrpcAsyncIOTransport, + transports.SipTrunksRestTransport, + ], +) +def test_sip_trunks_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.SipTrunksGrpcTransport, grpc_helpers), + (transports.SipTrunksGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_sip_trunks_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( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.SipTrunksGrpcTransport, transports.SipTrunksGrpcAsyncIOTransport], +) +def test_sip_trunks_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_sip_trunks_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.SipTrunksRestTransport( + 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_sip_trunks_host_no_port(transport_name): + client = SipTrunksClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "dialogflow.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://dialogflow.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_sip_trunks_host_with_port(transport_name): + client = SipTrunksClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "dialogflow.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://dialogflow.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_sip_trunks_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = SipTrunksClient( + credentials=creds1, + transport=transport_name, + ) + client2 = SipTrunksClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_sip_trunk._session + session2 = client2.transport.create_sip_trunk._session + assert session1 != session2 + session1 = client1.transport.delete_sip_trunk._session + session2 = client2.transport.delete_sip_trunk._session + assert session1 != session2 + session1 = client1.transport.list_sip_trunks._session + session2 = client2.transport.list_sip_trunks._session + assert session1 != session2 + session1 = client1.transport.get_sip_trunk._session + session2 = client2.transport.get_sip_trunk._session + assert session1 != session2 + session1 = client1.transport.update_sip_trunk._session + session2 = client2.transport.update_sip_trunk._session + assert session1 != session2 + + +def test_sip_trunks_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SipTrunksGrpcTransport( + 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_sip_trunks_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.SipTrunksGrpcAsyncIOTransport( + 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.SipTrunksGrpcTransport, transports.SipTrunksGrpcAsyncIOTransport], +) +def test_sip_trunks_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.SipTrunksGrpcTransport, transports.SipTrunksGrpcAsyncIOTransport], +) +def test_sip_trunks_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_sip_trunk_path(): + project = "squid" + location = "clam" + siptrunk = "whelk" + expected = "projects/{project}/locations/{location}/sipTrunks/{siptrunk}".format( + project=project, + location=location, + siptrunk=siptrunk, + ) + actual = SipTrunksClient.sip_trunk_path(project, location, siptrunk) + assert expected == actual + + +def test_parse_sip_trunk_path(): + expected = { + "project": "octopus", + "location": "oyster", + "siptrunk": "nudibranch", + } + path = SipTrunksClient.sip_trunk_path(**expected) + + # Check that the path construction is reversible. + actual = SipTrunksClient.parse_sip_trunk_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = SipTrunksClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = SipTrunksClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = SipTrunksClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = SipTrunksClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = SipTrunksClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = SipTrunksClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = SipTrunksClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = SipTrunksClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = SipTrunksClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format( + project=project, + ) + actual = SipTrunksClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = SipTrunksClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = SipTrunksClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "whelk" + location = "octopus" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = SipTrunksClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = SipTrunksClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = SipTrunksClient.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.SipTrunksTransport, "_prep_wrapped_messages" + ) as prep: + client = SipTrunksClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.SipTrunksTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = SipTrunksClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_cancel_operation(transport: str = "grpc"): + client = SipTrunksClient( + 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 = SipTrunksAsyncClient( + 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 = SipTrunksClient( + 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 = SipTrunksAsyncClient( + 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 = SipTrunksClient( + 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 = SipTrunksAsyncClient( + 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 = SipTrunksClient( + 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 = SipTrunksAsyncClient( + 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 = SipTrunksClient( + 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 = SipTrunksAsyncClient( + 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 = SipTrunksClient( + 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 = SipTrunksAsyncClient( + 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 = SipTrunksClient( + 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 = SipTrunksAsyncClient( + 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 = SipTrunksClient( + 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 = SipTrunksAsyncClient( + 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 = SipTrunksClient( + 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 = SipTrunksAsyncClient( + 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 = SipTrunksClient( + 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 = SipTrunksAsyncClient( + 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 = SipTrunksClient( + 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 = SipTrunksAsyncClient( + 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 = SipTrunksClient( + 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 = SipTrunksAsyncClient( + 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 = SipTrunksClient( + 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 = SipTrunksAsyncClient( + 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 = SipTrunksClient(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 = SipTrunksAsyncClient(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 = SipTrunksClient( + 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 = SipTrunksAsyncClient( + 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 = SipTrunksClient( + 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 = SipTrunksAsyncClient( + 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 = SipTrunksClient( + 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 = SipTrunksClient( + 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", + [ + (SipTrunksClient, transports.SipTrunksGrpcTransport), + (SipTrunksAsyncClient, transports.SipTrunksGrpcAsyncIOTransport), + ], +) +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-dialogflow/tests/unit/gapic/dialogflow_v2/test_tools.py b/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2/test_tools.py new file mode 100644 index 000000000000..a0405e11554a --- /dev/null +++ b/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2/test_tools.py @@ -0,0 +1,7194 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 + +from collections.abc import AsyncIterable, Iterable +import json +import math + +from google.api_core import api_core_version +from google.protobuf import json_format +import grpc +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest +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 + +from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +import google.auth +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.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.dialogflow_v2.services.tools import ( + ToolsAsyncClient, + ToolsClient, + pagers, + transports, +) +from google.cloud.dialogflow_v2.types import tool +from google.cloud.dialogflow_v2.types import tool as gcd_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 ToolsClient._get_default_mtls_endpoint(None) is None + assert ToolsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ( + ToolsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + ) + assert ( + ToolsClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + ToolsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ToolsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + + +def test__read_environment_variables(): + assert ToolsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert ToolsClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert ToolsClient._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: + ToolsClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + else: + assert ToolsClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert ToolsClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert ToolsClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert ToolsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + ToolsClient._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 ToolsClient._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 ToolsClient._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 ToolsClient._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 ToolsClient._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 ToolsClient._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 ToolsClient._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 ToolsClient._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 ToolsClient._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 ToolsClient._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 ToolsClient._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): + ToolsClient._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 ToolsClient._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 ToolsClient._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 ToolsClient._get_client_cert_source(None, False) is None + assert ToolsClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert ( + ToolsClient._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 ( + ToolsClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + ToolsClient._get_client_cert_source(mock_provided_cert_source, "true") + is mock_provided_cert_source + ) + + +@mock.patch.object( + ToolsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ToolsClient), +) +@mock.patch.object( + ToolsAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ToolsAsyncClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = ToolsClient._DEFAULT_UNIVERSE + default_endpoint = ToolsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = ToolsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + ToolsClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + ToolsClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == ToolsClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + ToolsClient._get_api_endpoint(None, None, default_universe, "auto") + == default_endpoint + ) + assert ( + ToolsClient._get_api_endpoint(None, None, default_universe, "always") + == ToolsClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + ToolsClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == ToolsClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + ToolsClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + ToolsClient._get_api_endpoint(None, None, default_universe, "never") + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + ToolsClient._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 ( + ToolsClient._get_universe_domain(client_universe_domain, universe_domain_env) + == client_universe_domain + ) + assert ( + ToolsClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ToolsClient._get_universe_domain(None, None) == ToolsClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + ToolsClient._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 = ToolsClient(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 = ToolsClient(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", + [ + (ToolsClient, "grpc"), + (ToolsAsyncClient, "grpc_asyncio"), + (ToolsClient, "rest"), + ], +) +def test_tools_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 == ( + "dialogflow.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://dialogflow.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.ToolsGrpcTransport, "grpc"), + (transports.ToolsGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ToolsRestTransport, "rest"), + ], +) +def test_tools_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", + [ + (ToolsClient, "grpc"), + (ToolsAsyncClient, "grpc_asyncio"), + (ToolsClient, "rest"), + ], +) +def test_tools_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 == ( + "dialogflow.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://dialogflow.googleapis.com" + ) + + +def test_tools_client_get_transport_class(): + transport = ToolsClient.get_transport_class() + available_transports = [ + transports.ToolsGrpcTransport, + transports.ToolsRestTransport, + ] + assert transport in available_transports + + transport = ToolsClient.get_transport_class("grpc") + assert transport == transports.ToolsGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ToolsClient, transports.ToolsGrpcTransport, "grpc"), + (ToolsAsyncClient, transports.ToolsGrpcAsyncIOTransport, "grpc_asyncio"), + (ToolsClient, transports.ToolsRestTransport, "rest"), + ], +) +@mock.patch.object( + ToolsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ToolsClient), +) +@mock.patch.object( + ToolsAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ToolsAsyncClient), +) +def test_tools_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(ToolsClient, "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(ToolsClient, "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", + [ + (ToolsClient, transports.ToolsGrpcTransport, "grpc", "true"), + ( + ToolsAsyncClient, + transports.ToolsGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (ToolsClient, transports.ToolsGrpcTransport, "grpc", "false"), + ( + ToolsAsyncClient, + transports.ToolsGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + (ToolsClient, transports.ToolsRestTransport, "rest", "true"), + (ToolsClient, transports.ToolsRestTransport, "rest", "false"), + ], +) +@mock.patch.object( + ToolsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ToolsClient), +) +@mock.patch.object( + ToolsAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ToolsAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_tools_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", [ToolsClient, ToolsAsyncClient]) +@mock.patch.object( + ToolsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ToolsClient) +) +@mock.patch.object( + ToolsAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ToolsAsyncClient) +) +def test_tools_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", [ToolsClient, ToolsAsyncClient]) +@mock.patch.object( + ToolsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ToolsClient), +) +@mock.patch.object( + ToolsAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ToolsAsyncClient), +) +def test_tools_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = ToolsClient._DEFAULT_UNIVERSE + default_endpoint = ToolsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = ToolsClient._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", + [ + (ToolsClient, transports.ToolsGrpcTransport, "grpc"), + (ToolsAsyncClient, transports.ToolsGrpcAsyncIOTransport, "grpc_asyncio"), + (ToolsClient, transports.ToolsRestTransport, "rest"), + ], +) +def test_tools_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", + [ + (ToolsClient, transports.ToolsGrpcTransport, "grpc", grpc_helpers), + ( + ToolsAsyncClient, + transports.ToolsGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + (ToolsClient, transports.ToolsRestTransport, "rest", None), + ], +) +def test_tools_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_tools_client_client_options_from_dict(): + with mock.patch( + "google.cloud.dialogflow_v2.services.tools.transports.ToolsGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = ToolsClient(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", + [ + (ToolsClient, transports.ToolsGrpcTransport, "grpc", grpc_helpers), + ( + ToolsAsyncClient, + transports.ToolsGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_tools_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( + "dialogflow.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + scopes=None, + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gcd_tool.CreateToolRequest, + dict, + ], +) +def test_create_tool(request_type, transport: str = "grpc"): + client = ToolsClient( + 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 = gcd_tool.Tool( + name="name_value", + tool_key="tool_key_value", + display_name="display_name_value", + description="description_value", + satisfies_pzs=True, + satisfies_pzi=True, + ) + 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 = gcd_tool.CreateToolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_tool.Tool) + assert response.name == "name_value" + assert response.tool_key == "tool_key_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True + + +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 = ToolsClient( + 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 = gcd_tool.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] == gcd_tool.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 = ToolsClient( + 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 = ToolsAsyncClient( + 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=gcd_tool.CreateToolRequest +): + client = ToolsAsyncClient( + 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( + gcd_tool.Tool( + name="name_value", + tool_key="tool_key_value", + display_name="display_name_value", + description="description_value", + satisfies_pzs=True, + satisfies_pzi=True, + ) + ) + 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 = gcd_tool.CreateToolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_tool.Tool) + assert response.name == "name_value" + assert response.tool_key == "tool_key_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True + + +@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 = ToolsClient( + 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 = gcd_tool.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 = gcd_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 = ToolsAsyncClient( + 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 = gcd_tool.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(gcd_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 = ToolsClient( + 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 = gcd_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=gcd_tool.Tool(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 = gcd_tool.Tool(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 = ToolsClient( + 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( + gcd_tool.CreateToolRequest(), + parent="parent_value", + tool=gcd_tool.Tool(name="name_value"), + tool_id="tool_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_tool_flattened_async(): + client = ToolsAsyncClient( + 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 = gcd_tool.Tool() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_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=gcd_tool.Tool(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 = gcd_tool.Tool(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 = ToolsAsyncClient( + 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( + gcd_tool.CreateToolRequest(), + parent="parent_value", + tool=gcd_tool.Tool(name="name_value"), + tool_id="tool_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + tool.GetToolRequest, + dict, + ], +) +def test_get_tool(request_type, transport: str = "grpc"): + client = ToolsClient( + 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", + tool_key="tool_key_value", + display_name="display_name_value", + description="description_value", + satisfies_pzs=True, + satisfies_pzi=True, + ) + 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 = tool.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.tool_key == "tool_key_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True + + +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 = ToolsClient( + 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.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] == tool.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 = ToolsClient( + 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 = ToolsAsyncClient( + 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=tool.GetToolRequest +): + client = ToolsAsyncClient( + 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", + tool_key="tool_key_value", + display_name="display_name_value", + description="description_value", + satisfies_pzs=True, + satisfies_pzi=True, + ) + ) + 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 = tool.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.tool_key == "tool_key_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True + + +@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 = ToolsClient( + 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.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 = ToolsAsyncClient( + 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.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 = ToolsClient( + 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 = ToolsClient( + 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( + tool.GetToolRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_tool_flattened_async(): + client = ToolsAsyncClient( + 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 = ToolsAsyncClient( + 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( + tool.GetToolRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + tool.ListToolsRequest, + dict, + ], +) +def test_list_tools(request_type, transport: str = "grpc"): + client = ToolsClient( + 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 = tool.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 = tool.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 = ToolsClient( + 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.ListToolsRequest( + parent="parent_value", + page_token="page_token_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] == tool.ListToolsRequest( + parent="parent_value", + page_token="page_token_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 = ToolsClient( + 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 = ToolsAsyncClient( + 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=tool.ListToolsRequest +): + client = ToolsAsyncClient( + 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( + tool.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 = tool.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 = ToolsClient( + 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.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 = tool.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 = ToolsAsyncClient( + 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.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( + tool.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 = ToolsClient( + 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 = tool.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 = ToolsClient( + 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( + tool.ListToolsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_tools_flattened_async(): + client = ToolsAsyncClient( + 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 = tool.ListToolsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + tool.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 = ToolsAsyncClient( + 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( + tool.ListToolsRequest(), + parent="parent_value", + ) + + +def test_list_tools_pager(transport_name: str = "grpc"): + client = ToolsClient( + 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 = ( + tool.ListToolsResponse( + tools=[ + tool.Tool(), + tool.Tool(), + tool.Tool(), + ], + next_page_token="abc", + ), + tool.ListToolsResponse( + tools=[], + next_page_token="def", + ), + tool.ListToolsResponse( + tools=[ + tool.Tool(), + ], + next_page_token="ghi", + ), + tool.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 = ToolsClient( + 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 = ( + tool.ListToolsResponse( + tools=[ + tool.Tool(), + tool.Tool(), + tool.Tool(), + ], + next_page_token="abc", + ), + tool.ListToolsResponse( + tools=[], + next_page_token="def", + ), + tool.ListToolsResponse( + tools=[ + tool.Tool(), + ], + next_page_token="ghi", + ), + tool.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 = ToolsAsyncClient( + 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 = ( + tool.ListToolsResponse( + tools=[ + tool.Tool(), + tool.Tool(), + tool.Tool(), + ], + next_page_token="abc", + ), + tool.ListToolsResponse( + tools=[], + next_page_token="def", + ), + tool.ListToolsResponse( + tools=[ + tool.Tool(), + ], + next_page_token="ghi", + ), + tool.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 = ToolsAsyncClient( + 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 = ( + tool.ListToolsResponse( + tools=[ + tool.Tool(), + tool.Tool(), + tool.Tool(), + ], + next_page_token="abc", + ), + tool.ListToolsResponse( + tools=[], + next_page_token="def", + ), + tool.ListToolsResponse( + tools=[ + tool.Tool(), + ], + next_page_token="ghi", + ), + tool.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", + [ + tool.DeleteToolRequest, + dict, + ], +) +def test_delete_tool(request_type, transport: str = "grpc"): + client = ToolsClient( + 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 = tool.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 = ToolsClient( + 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.DeleteToolRequest( + 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.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] == tool.DeleteToolRequest( + name="name_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 = ToolsClient( + 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 = ToolsAsyncClient( + 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=tool.DeleteToolRequest +): + client = ToolsAsyncClient( + 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 = tool.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 = ToolsClient( + 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.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 = ToolsAsyncClient( + 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.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 = ToolsClient( + 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 = ToolsClient( + 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( + tool.DeleteToolRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_tool_flattened_async(): + client = ToolsAsyncClient( + 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 = ToolsAsyncClient( + 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( + tool.DeleteToolRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gcd_tool.UpdateToolRequest, + dict, + ], +) +def test_update_tool(request_type, transport: str = "grpc"): + client = ToolsClient( + 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 = gcd_tool.Tool( + name="name_value", + tool_key="tool_key_value", + display_name="display_name_value", + description="description_value", + satisfies_pzs=True, + satisfies_pzi=True, + ) + 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 = gcd_tool.UpdateToolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_tool.Tool) + assert response.name == "name_value" + assert response.tool_key == "tool_key_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True + + +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 = ToolsClient( + 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 = gcd_tool.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] == gcd_tool.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 = ToolsClient( + 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 = ToolsAsyncClient( + 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=gcd_tool.UpdateToolRequest +): + client = ToolsAsyncClient( + 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( + gcd_tool.Tool( + name="name_value", + tool_key="tool_key_value", + display_name="display_name_value", + description="description_value", + satisfies_pzs=True, + satisfies_pzi=True, + ) + ) + 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 = gcd_tool.UpdateToolRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, gcd_tool.Tool) + assert response.name == "name_value" + assert response.tool_key == "tool_key_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True + + +@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 = ToolsClient( + 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 = gcd_tool.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 = gcd_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 = ToolsAsyncClient( + 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 = gcd_tool.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(gcd_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 = ToolsClient( + 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 = gcd_tool.Tool() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_tool( + tool=gcd_tool.Tool(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 = gcd_tool.Tool(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 = ToolsClient( + 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( + gcd_tool.UpdateToolRequest(), + tool=gcd_tool.Tool(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_tool_flattened_async(): + client = ToolsAsyncClient( + 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 = gcd_tool.Tool() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcd_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=gcd_tool.Tool(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 = gcd_tool.Tool(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 = ToolsAsyncClient( + 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( + gcd_tool.UpdateToolRequest(), + tool=gcd_tool.Tool(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_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 = ToolsClient( + 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=gcd_tool.CreateToolRequest): + transport_class = transports.ToolsRestTransport + + 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 = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcd_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 = gcd_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.ToolsRestTransport( + 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 = ToolsClient( + 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 = gcd_tool.Tool() + + # 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", + tool=gcd_tool.Tool(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 = gcd_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/v2/{parent=projects/*/locations/*}/tools" % client.transport._host, + args[1], + ) + + +def test_create_tool_rest_flattened_error(transport: str = "rest"): + client = ToolsClient( + 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( + gcd_tool.CreateToolRequest(), + parent="parent_value", + tool=gcd_tool.Tool(name="name_value"), + tool_id="tool_id_value", + ) + + +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 = ToolsClient( + 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=tool.GetToolRequest): + transport_class = transports.ToolsRestTransport + + 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 = ToolsClient( + 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.ToolsRestTransport( + 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 = ToolsClient( + 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/tools/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 = 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/v2/{name=projects/*/locations/*/tools/*}" % client.transport._host, + args[1], + ) + + +def test_get_tool_rest_flattened_error(transport: str = "rest"): + client = ToolsClient( + 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( + tool.GetToolRequest(), + 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 = ToolsClient( + 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=tool.ListToolsRequest): + transport_class = transports.ToolsRestTransport + + 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( + ( + "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 = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = tool.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 = tool.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.ToolsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_tools._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_tools_rest_flattened(): + client = ToolsClient( + 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.ListToolsResponse() + + # 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 = tool.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/v2/{parent=projects/*/locations/*}/tools" % client.transport._host, + args[1], + ) + + +def test_list_tools_rest_flattened_error(transport: str = "rest"): + client = ToolsClient( + 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( + tool.ListToolsRequest(), + parent="parent_value", + ) + + +def test_list_tools_rest_pager(transport: str = "rest"): + client = ToolsClient( + 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 = ( + tool.ListToolsResponse( + tools=[ + tool.Tool(), + tool.Tool(), + tool.Tool(), + ], + next_page_token="abc", + ), + tool.ListToolsResponse( + tools=[], + next_page_token="def", + ), + tool.ListToolsResponse( + tools=[ + tool.Tool(), + ], + next_page_token="ghi", + ), + tool.ListToolsResponse( + tools=[ + tool.Tool(), + tool.Tool(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(tool.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"} + + 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_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 = ToolsClient( + 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=tool.DeleteToolRequest): + transport_class = transports.ToolsRestTransport + + 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) + 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 = ToolsClient( + 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.ToolsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_tool._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_delete_tool_rest_flattened(): + client = ToolsClient( + 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/tools/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 = "" + response_value._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/v2/{name=projects/*/locations/*/tools/*}" % client.transport._host, + args[1], + ) + + +def test_delete_tool_rest_flattened_error(transport: str = "rest"): + client = ToolsClient( + 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( + tool.DeleteToolRequest(), + name="name_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 = ToolsClient( + 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=gcd_tool.UpdateToolRequest): + transport_class = transports.ToolsRestTransport + + 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 = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcd_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 = gcd_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.ToolsRestTransport( + 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 = ToolsClient( + 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 = gcd_tool.Tool() + + # get arguments that satisfy an http rule for this method + sample_request = { + "tool": {"name": "projects/sample1/locations/sample2/tools/sample3"} + } + + # get truthy value for each flattened field + mock_args = dict( + tool=gcd_tool.Tool(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 = gcd_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/v2/{tool.name=projects/*/locations/*/tools/*}" % client.transport._host, + args[1], + ) + + +def test_update_tool_rest_flattened_error(transport: str = "rest"): + client = ToolsClient( + 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( + gcd_tool.UpdateToolRequest(), + tool=gcd_tool.Tool(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ToolsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ToolsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ToolsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ToolsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ToolsClient( + 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 = ToolsClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ToolsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ToolsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ToolsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ToolsClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ToolsGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ToolsGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ToolsGrpcTransport, + transports.ToolsGrpcAsyncIOTransport, + transports.ToolsRestTransport, + ], +) +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 = ToolsClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = ToolsClient( + 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_create_tool_empty_call_grpc(): + client = ToolsClient( + 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 = gcd_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 = gcd_tool.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_get_tool_empty_call_grpc(): + client = ToolsClient( + 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 = tool.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_tools_empty_call_grpc(): + client = ToolsClient( + 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 = tool.ListToolsResponse() + client.list_tools(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tool.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_delete_tool_empty_call_grpc(): + client = ToolsClient( + 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 = tool.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_update_tool_empty_call_grpc(): + client = ToolsClient( + 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 = gcd_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 = gcd_tool.UpdateToolRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = ToolsAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = ToolsAsyncClient( + 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_create_tool_empty_call_grpc_asyncio(): + client = ToolsAsyncClient( + 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( + gcd_tool.Tool( + name="name_value", + tool_key="tool_key_value", + display_name="display_name_value", + description="description_value", + satisfies_pzs=True, + satisfies_pzi=True, + ) + ) + await client.create_tool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcd_tool.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_get_tool_empty_call_grpc_asyncio(): + client = ToolsAsyncClient( + 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", + tool_key="tool_key_value", + display_name="display_name_value", + description="description_value", + satisfies_pzs=True, + satisfies_pzi=True, + ) + ) + await client.get_tool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = tool.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_tools_empty_call_grpc_asyncio(): + client = ToolsAsyncClient( + 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( + tool.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 = tool.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_delete_tool_empty_call_grpc_asyncio(): + client = ToolsAsyncClient( + 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 = tool.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_update_tool_empty_call_grpc_asyncio(): + client = ToolsAsyncClient( + 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( + gcd_tool.Tool( + name="name_value", + tool_key="tool_key_value", + display_name="display_name_value", + description="description_value", + satisfies_pzs=True, + satisfies_pzi=True, + ) + ) + await client.update_tool(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcd_tool.UpdateToolRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = ToolsClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_tool_rest_bad_request(request_type=gcd_tool.CreateToolRequest): + client = ToolsClient( + 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_tool(request) + + +@pytest.mark.parametrize( + "request_type", + [ + gcd_tool.CreateToolRequest, + dict, + ], +) +def test_create_tool_rest_call_success(request_type): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["tool"] = { + "name": "name_value", + "tool_key": "tool_key_value", + "display_name": "display_name_value", + "description": "description_value", + "action_confirmation_requirement": {}, + "extension_spec": {"name": "name_value"}, + "function_spec": { + "input_schema": {"fields": {}}, + "output_schema": {}, + "method_type": 1, + }, + "connector_spec": { + "name": "name_value", + "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"], + } + ], + }, + "open_api_spec": { + "text_schema": "text_schema_value", + "authentication": { + "api_key_config": { + "key_name": "key_name_value", + "api_key": "api_key_value", + "secret_version_for_api_key": "secret_version_for_api_key_value", + "request_location": 1, + }, + "oauth_config": { + "oauth_grant_type": 1, + "client_id": "client_id_value", + "client_secret": "client_secret_value", + "secret_version_for_client_secret": "secret_version_for_client_secret_value", + "token_endpoint": "token_endpoint_value", + "scopes": ["scopes_value1", "scopes_value2"], + }, + "service_agent_auth_config": {"service_agent_auth": 1}, + "bearer_token_config": { + "token": "token_value", + "secret_version_for_token": "secret_version_for_token_value", + }, + }, + "tls_config": { + "ca_certs": [ + {"display_name": "display_name_value", "cert": b"cert_blob"} + ] + }, + "service_directory_config": {"service": "service_value"}, + }, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "satisfies_pzs": True, + "satisfies_pzi": 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 = gcd_tool.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 = gcd_tool.Tool( + name="name_value", + tool_key="tool_key_value", + display_name="display_name_value", + description="description_value", + satisfies_pzs=True, + satisfies_pzi=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 = gcd_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, gcd_tool.Tool) + assert response.name == "name_value" + assert response.tool_key == "tool_key_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_tool_rest_interceptors(null_interceptor): + transport = transports.ToolsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ToolsRestInterceptor(), + ) + client = ToolsClient(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.ToolsRestInterceptor, "post_create_tool" + ) as post, mock.patch.object( + transports.ToolsRestInterceptor, "post_create_tool_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.ToolsRestInterceptor, "pre_create_tool" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcd_tool.CreateToolRequest.pb(gcd_tool.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 = gcd_tool.Tool.to_json(gcd_tool.Tool()) + req.return_value.content = return_value + + request = gcd_tool.CreateToolRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcd_tool.Tool() + post_with_metadata.return_value = gcd_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_get_tool_rest_bad_request(request_type=tool.GetToolRequest): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/tools/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_tool(request) + + +@pytest.mark.parametrize( + "request_type", + [ + tool.GetToolRequest, + dict, + ], +) +def test_get_tool_rest_call_success(request_type): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/tools/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.Tool( + name="name_value", + tool_key="tool_key_value", + display_name="display_name_value", + description="description_value", + satisfies_pzs=True, + satisfies_pzi=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 = 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.tool_key == "tool_key_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_tool_rest_interceptors(null_interceptor): + transport = transports.ToolsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ToolsRestInterceptor(), + ) + client = ToolsClient(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.ToolsRestInterceptor, "post_get_tool" + ) as post, mock.patch.object( + transports.ToolsRestInterceptor, "post_get_tool_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.ToolsRestInterceptor, "pre_get_tool" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = tool.GetToolRequest.pb(tool.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 = tool.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_tools_rest_bad_request(request_type=tool.ListToolsRequest): + client = ToolsClient( + 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_tools(request) + + +@pytest.mark.parametrize( + "request_type", + [ + tool.ListToolsRequest, + dict, + ], +) +def test_list_tools_rest_call_success(request_type): + client = ToolsClient( + 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 = tool.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 = tool.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.ToolsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ToolsRestInterceptor(), + ) + client = ToolsClient(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.ToolsRestInterceptor, "post_list_tools" + ) as post, mock.patch.object( + transports.ToolsRestInterceptor, "post_list_tools_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.ToolsRestInterceptor, "pre_list_tools" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = tool.ListToolsRequest.pb(tool.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 = tool.ListToolsResponse.to_json(tool.ListToolsResponse()) + req.return_value.content = return_value + + request = tool.ListToolsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = tool.ListToolsResponse() + post_with_metadata.return_value = tool.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_delete_tool_rest_bad_request(request_type=tool.DeleteToolRequest): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/tools/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_tool(request) + + +@pytest.mark.parametrize( + "request_type", + [ + tool.DeleteToolRequest, + dict, + ], +) +def test_delete_tool_rest_call_success(request_type): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/tools/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 = 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.ToolsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ToolsRestInterceptor(), + ) + client = ToolsClient(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.ToolsRestInterceptor, "pre_delete_tool" + ) as pre: + pre.assert_not_called() + pb_message = tool.DeleteToolRequest.pb(tool.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 = tool.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_update_tool_rest_bad_request(request_type=gcd_tool.UpdateToolRequest): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "tool": {"name": "projects/sample1/locations/sample2/tools/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_tool(request) + + +@pytest.mark.parametrize( + "request_type", + [ + gcd_tool.UpdateToolRequest, + dict, + ], +) +def test_update_tool_rest_call_success(request_type): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "tool": {"name": "projects/sample1/locations/sample2/tools/sample3"} + } + request_init["tool"] = { + "name": "projects/sample1/locations/sample2/tools/sample3", + "tool_key": "tool_key_value", + "display_name": "display_name_value", + "description": "description_value", + "action_confirmation_requirement": {}, + "extension_spec": {"name": "name_value"}, + "function_spec": { + "input_schema": {"fields": {}}, + "output_schema": {}, + "method_type": 1, + }, + "connector_spec": { + "name": "name_value", + "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"], + } + ], + }, + "open_api_spec": { + "text_schema": "text_schema_value", + "authentication": { + "api_key_config": { + "key_name": "key_name_value", + "api_key": "api_key_value", + "secret_version_for_api_key": "secret_version_for_api_key_value", + "request_location": 1, + }, + "oauth_config": { + "oauth_grant_type": 1, + "client_id": "client_id_value", + "client_secret": "client_secret_value", + "secret_version_for_client_secret": "secret_version_for_client_secret_value", + "token_endpoint": "token_endpoint_value", + "scopes": ["scopes_value1", "scopes_value2"], + }, + "service_agent_auth_config": {"service_agent_auth": 1}, + "bearer_token_config": { + "token": "token_value", + "secret_version_for_token": "secret_version_for_token_value", + }, + }, + "tls_config": { + "ca_certs": [ + {"display_name": "display_name_value", "cert": b"cert_blob"} + ] + }, + "service_directory_config": {"service": "service_value"}, + }, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "satisfies_pzs": True, + "satisfies_pzi": 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 = gcd_tool.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 = gcd_tool.Tool( + name="name_value", + tool_key="tool_key_value", + display_name="display_name_value", + description="description_value", + satisfies_pzs=True, + satisfies_pzi=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 = gcd_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, gcd_tool.Tool) + assert response.name == "name_value" + assert response.tool_key == "tool_key_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_tool_rest_interceptors(null_interceptor): + transport = transports.ToolsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.ToolsRestInterceptor(), + ) + client = ToolsClient(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.ToolsRestInterceptor, "post_update_tool" + ) as post, mock.patch.object( + transports.ToolsRestInterceptor, "post_update_tool_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.ToolsRestInterceptor, "pre_update_tool" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcd_tool.UpdateToolRequest.pb(gcd_tool.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 = gcd_tool.Tool.to_json(gcd_tool.Tool()) + req.return_value.content = return_value + + request = gcd_tool.UpdateToolRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcd_tool.Tool() + post_with_metadata.return_value = gcd_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_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = ToolsClient( + 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 = ToolsClient( + 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 = ToolsClient( + 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 = ToolsClient( + 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 = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/operations/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.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/operations/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 = 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_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/operations/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_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/operations/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.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 = ToolsClient( + 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_operations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.ListOperationsRequest, + dict, + ], +) +def test_list_operations_rest(request_type): + client = ToolsClient( + 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 = 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 = ToolsClient( + 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_create_tool_empty_call_rest(): + client = ToolsClient( + 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 = gcd_tool.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_get_tool_empty_call_rest(): + client = ToolsClient( + 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 = tool.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_tools_empty_call_rest(): + client = ToolsClient( + 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 = tool.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_delete_tool_empty_call_rest(): + client = ToolsClient( + 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 = tool.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_update_tool_empty_call_rest(): + client = ToolsClient( + 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 = gcd_tool.UpdateToolRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ToolsGrpcTransport, + ) + + +def test_tools_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ToolsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_tools_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.dialogflow_v2.services.tools.transports.ToolsTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.ToolsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "create_tool", + "get_tool", + "list_tools", + "delete_tool", + "update_tool", + "get_location", + "list_locations", + "get_operation", + "cancel_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_tools_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.dialogflow_v2.services.tools.transports.ToolsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ToolsTransport( + 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/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +def test_tools_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.dialogflow_v2.services.tools.transports.ToolsTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ToolsTransport() + adc.assert_called_once() + + +def test_tools_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) + ToolsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ToolsGrpcTransport, + transports.ToolsGrpcAsyncIOTransport, + ], +) +def test_tools_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/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ToolsGrpcTransport, + transports.ToolsGrpcAsyncIOTransport, + transports.ToolsRestTransport, + ], +) +def test_tools_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.ToolsGrpcTransport, grpc_helpers), + (transports.ToolsGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_tools_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( + "dialogflow.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/dialogflow", + ), + scopes=["1", "2"], + default_host="dialogflow.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.ToolsGrpcTransport, transports.ToolsGrpcAsyncIOTransport], +) +def test_tools_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_tools_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.ToolsRestTransport( + 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_tools_host_no_port(transport_name): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "dialogflow.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://dialogflow.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_tools_host_with_port(transport_name): + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="dialogflow.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "dialogflow.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://dialogflow.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_tools_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ToolsClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ToolsClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_tool._session + session2 = client2.transport.create_tool._session + assert session1 != session2 + session1 = client1.transport.get_tool._session + session2 = client2.transport.get_tool._session + assert session1 != session2 + session1 = client1.transport.list_tools._session + session2 = client2.transport.list_tools._session + assert session1 != session2 + session1 = client1.transport.delete_tool._session + session2 = client2.transport.delete_tool._session + assert session1 != session2 + session1 = client1.transport.update_tool._session + session2 = client2.transport.update_tool._session + assert session1 != session2 + + +def test_tools_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ToolsGrpcTransport( + 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_tools_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.ToolsGrpcAsyncIOTransport( + 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.ToolsGrpcTransport, transports.ToolsGrpcAsyncIOTransport], +) +def test_tools_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.ToolsGrpcTransport, transports.ToolsGrpcAsyncIOTransport], +) +def test_tools_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_secret_version_path(): + project = "squid" + secret = "clam" + version = "whelk" + expected = "projects/{project}/secrets/{secret}/versions/{version}".format( + project=project, + secret=secret, + version=version, + ) + actual = ToolsClient.secret_version_path(project, secret, version) + assert expected == actual + + +def test_parse_secret_version_path(): + expected = { + "project": "octopus", + "secret": "oyster", + "version": "nudibranch", + } + path = ToolsClient.secret_version_path(**expected) + + # Check that the path construction is reversible. + actual = ToolsClient.parse_secret_version_path(path) + assert expected == actual + + +def test_service_path(): + project = "cuttlefish" + location = "mussel" + namespace = "winkle" + service = "nautilus" + expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format( + project=project, + location=location, + namespace=namespace, + service=service, + ) + actual = ToolsClient.service_path(project, location, namespace, service) + assert expected == actual + + +def test_parse_service_path(): + expected = { + "project": "scallop", + "location": "abalone", + "namespace": "squid", + "service": "clam", + } + path = ToolsClient.service_path(**expected) + + # Check that the path construction is reversible. + actual = ToolsClient.parse_service_path(path) + assert expected == actual + + +def test_tool_path(): + project = "whelk" + location = "octopus" + tool = "oyster" + expected = "projects/{project}/locations/{location}/tools/{tool}".format( + project=project, + location=location, + tool=tool, + ) + actual = ToolsClient.tool_path(project, location, tool) + assert expected == actual + + +def test_parse_tool_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "tool": "mussel", + } + path = ToolsClient.tool_path(**expected) + + # Check that the path construction is reversible. + actual = ToolsClient.parse_tool_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "winkle" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = ToolsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "nautilus", + } + path = ToolsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ToolsClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "scallop" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = ToolsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "abalone", + } + path = ToolsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ToolsClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "squid" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = ToolsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "clam", + } + path = ToolsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ToolsClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "whelk" + expected = "projects/{project}".format( + project=project, + ) + actual = ToolsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "octopus", + } + path = ToolsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ToolsClient.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 = ToolsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + } + path = ToolsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ToolsClient.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.ToolsTransport, "_prep_wrapped_messages") as prep: + client = ToolsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.ToolsTransport, "_prep_wrapped_messages") as prep: + transport_class = ToolsClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_cancel_operation(transport: str = "grpc"): + client = ToolsClient( + 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 = ToolsAsyncClient( + 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 = ToolsClient( + 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 = ToolsAsyncClient( + 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 = ToolsClient( + 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 = ToolsAsyncClient( + 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 = ToolsClient( + 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 = ToolsAsyncClient( + 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 = ToolsClient( + 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 = ToolsAsyncClient( + 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 = ToolsClient( + 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 = ToolsAsyncClient( + 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 = ToolsClient( + 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 = ToolsAsyncClient( + 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 = ToolsClient( + 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 = ToolsAsyncClient( + 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 = ToolsClient( + 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 = ToolsAsyncClient( + 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 = ToolsClient( + 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 = ToolsAsyncClient( + 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 = ToolsClient( + 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 = ToolsAsyncClient( + 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 = ToolsClient( + 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 = ToolsAsyncClient( + 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 = ToolsClient( + 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 = ToolsAsyncClient( + 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 = ToolsClient(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 = ToolsAsyncClient(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 = ToolsClient( + 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 = ToolsAsyncClient( + 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 = ToolsClient( + 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 = ToolsAsyncClient( + 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 = ToolsClient( + 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 = ToolsClient( + 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", + [ + (ToolsClient, transports.ToolsGrpcTransport), + (ToolsAsyncClient, transports.ToolsGrpcAsyncIOTransport), + ], +) +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-dialogflow/tests/unit/gapic/dialogflow_v2beta1/test_answer_records.py b/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2beta1/test_answer_records.py index 052c2a386bd0..172557a68d34 100644 --- a/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2beta1/test_answer_records.py +++ b/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2beta1/test_answer_records.py @@ -3769,6 +3769,7 @@ def test_update_answer_record_rest_call_success(request_type): } ] }, + "triggering_event": 1, } ], "agent_action_suggestions": [ diff --git a/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2beta1/test_generator_evaluations.py b/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2beta1/test_generator_evaluations.py index 007f4494bdc1..f911524d7164 100644 --- a/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2beta1/test_generator_evaluations.py +++ b/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2beta1/test_generator_evaluations.py @@ -4247,6 +4247,7 @@ def test_create_generator_evaluation_rest_call_success(request_type): } ] }, + "triggering_event": 1, } ], "version": "version_value", diff --git a/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2beta1/test_generators.py b/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2beta1/test_generators.py index cba464d180ec..3779551ace13 100644 --- a/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2beta1/test_generators.py +++ b/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2beta1/test_generators.py @@ -4565,6 +4565,7 @@ def test_create_generator_rest_call_success(request_type): } ] }, + "triggering_event": 1, } ], "version": "version_value", @@ -5259,6 +5260,7 @@ def test_update_generator_rest_call_success(request_type): } ] }, + "triggering_event": 1, } ], "version": "version_value", diff --git a/packages/google-cloud-dlp/google/cloud/dlp_v2/types/dlp.py b/packages/google-cloud-dlp/google/cloud/dlp_v2/types/dlp.py index 374befdc883d..8d1fd828e2f0 100644 --- a/packages/google-cloud-dlp/google/cloud/dlp_v2/types/dlp.py +++ b/packages/google-cloud-dlp/google/cloud/dlp_v2/types/dlp.py @@ -584,7 +584,7 @@ class RelationalOperator(proto.Enum): class MatchingType(proto.Enum): r"""Type of the match which can be applied to different ways of matching, like Dictionary, regular expression and intersecting - with findings of another info type. + with findings of another infoType. Values: MATCHING_TYPE_UNSPECIFIED (0): @@ -593,27 +593,27 @@ class MatchingType(proto.Enum): Full match. - Dictionary: join of Dictionary results matched - complete finding quote + the complete finding quote - Regex: all regex matches fill a finding quote - start to end - - Exclude info type: completely inside affecting - info types findings + from start to end + - Exclude infoType: completely inside affecting + infoTypes findings MATCHING_TYPE_PARTIAL_MATCH (2): Partial match. - Dictionary: at least one of the tokens in the finding matches - Regex: substring of the finding matches - - Exclude info type: intersects with affecting - info types findings + - Exclude infoType: intersects with affecting + infoTypes findings MATCHING_TYPE_INVERSE_MATCH (3): Inverse match. - Dictionary: no tokens in the finding match the dictionary - Regex: finding doesn't match the regex - - Exclude info type: no intersection with - affecting info types findings + - Exclude infoType: no intersection with + affecting infoTypes findings """ MATCHING_TYPE_UNSPECIFIED = 0 MATCHING_TYPE_FULL_MATCH = 1 @@ -6872,7 +6872,9 @@ class Action(proto.Message): This field is a member of `oneof`_ ``action``. publish_findings_to_cloud_data_catalog (google.cloud.dlp_v2.types.Action.PublishFindingsToCloudDataCatalog): - Publish findings to Cloud Datahub. + Deprecated because Data Catalog is being turned down. Use + publish_findings_to_dataplex_catalog to publish findings to + Dataplex Universal Catalog. This field is a member of `oneof`_ ``action``. publish_findings_to_dataplex_catalog (google.cloud.dlp_v2.types.Action.PublishFindingsToDataplexCatalog): @@ -10839,13 +10841,16 @@ class VertexDatasetRegex(proto.Message): class VertexDatasetResourceReference(proto.Message): - r"""Identifies a single Vertex AI dataset. + r"""Identifies a single Vertex AI resource. Only datasets are + supported. Attributes: dataset_resource_name (str): - Required. The name of the dataset resource. - If set within a project-level configuration, the - specified resource must be within the project. + Required. The name of the Vertex AI resource. If set within + a project-level configuration, the specified resource must + be within the project. Examples: + + - ``projects/{project}/locations/{location}/datasets/{dataset}`` """ dataset_resource_name: str = proto.Field( @@ -14508,8 +14513,8 @@ class DataSourceType(proto.Message): Attributes: data_source (str): - Output only. An identifying string to the type of resource - being profiled. Current values: + A string that identifies the type of resource being + profiled. Current values: - google/bigquery/table - google/project diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics/__init__.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics/__init__.py index 6ec003cdf98f..952feba5a892 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics/__init__.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics/__init__.py @@ -30,6 +30,9 @@ from google.cloud.geminidataanalytics_v1alpha.services.data_chat_service.client import ( DataChatServiceClient, ) +from google.cloud.geminidataanalytics_v1alpha.types.agent_context import ( + AgentContextReference, +) from google.cloud.geminidataanalytics_v1alpha.types.context import ( AnalysisOptions, ChartOptions, @@ -38,6 +41,7 @@ DatasourceOptions, ExampleQuery, GlossaryTerm, + LookerGoldenQuery, LookerQuery, ) from google.cloud.geminidataanalytics_v1alpha.types.conversation import ( @@ -102,8 +106,12 @@ UserMessage, ) from google.cloud.geminidataanalytics_v1alpha.types.datasource import ( + AlloyDbDatabaseReference, + AlloyDbReference, BigQueryTableReference, BigQueryTableReferences, + CloudSqlDatabaseReference, + CloudSqlReference, DataFilter, DataFilterType, Datasource, @@ -113,6 +121,8 @@ LookerExploreReferences, PrivateLookerInstanceInfo, Schema, + SpannerDatabaseReference, + SpannerReference, StudioDatasourceReference, StudioDatasourceReferences, ) @@ -122,6 +132,7 @@ "DataAgentServiceAsyncClient", "DataChatServiceClient", "DataChatServiceAsyncClient", + "AgentContextReference", "AnalysisOptions", "ChartOptions", "Context", @@ -129,6 +140,7 @@ "DatasourceOptions", "ExampleQuery", "GlossaryTerm", + "LookerGoldenQuery", "LookerQuery", "Conversation", "CreateConversationRequest", @@ -181,8 +193,12 @@ "SystemMessage", "TextMessage", "UserMessage", + "AlloyDbDatabaseReference", + "AlloyDbReference", "BigQueryTableReference", "BigQueryTableReferences", + "CloudSqlDatabaseReference", + "CloudSqlReference", "DataFilter", "Datasource", "DatasourceReferences", @@ -191,6 +207,8 @@ "LookerExploreReferences", "PrivateLookerInstanceInfo", "Schema", + "SpannerDatabaseReference", + "SpannerReference", "StudioDatasourceReference", "StudioDatasourceReferences", "DataFilterType", diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/__init__.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/__init__.py index 3f9125aeb1a4..130f9fe047be 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/__init__.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/__init__.py @@ -36,6 +36,7 @@ DataChatServiceAsyncClient, DataChatServiceClient, ) +from .types.agent_context import AgentContextReference from .types.context import ( AnalysisOptions, ChartOptions, @@ -44,6 +45,7 @@ DatasourceOptions, ExampleQuery, GlossaryTerm, + LookerGoldenQuery, LookerQuery, ) from .types.conversation import ( @@ -103,8 +105,12 @@ UserMessage, ) from .types.datasource import ( + AlloyDbDatabaseReference, + AlloyDbReference, BigQueryTableReference, BigQueryTableReferences, + CloudSqlDatabaseReference, + CloudSqlReference, DataFilter, DataFilterType, Datasource, @@ -114,6 +120,8 @@ LookerExploreReferences, PrivateLookerInstanceInfo, Schema, + SpannerDatabaseReference, + SpannerReference, StudioDatasourceReference, StudioDatasourceReferences, ) @@ -215,6 +223,9 @@ def _get_version(dependency_name): __all__ = ( "DataAgentServiceAsyncClient", "DataChatServiceAsyncClient", + "AgentContextReference", + "AlloyDbDatabaseReference", + "AlloyDbReference", "AnalysisEvent", "AnalysisMessage", "AnalysisOptions", @@ -229,6 +240,8 @@ def _get_version(dependency_name): "ChartResult", "ChatRequest", "ClientManagedResourceContext", + "CloudSqlDatabaseReference", + "CloudSqlReference", "Context", "Conversation", "ConversationOptions", @@ -270,6 +283,7 @@ def _get_version(dependency_name): "ListMessagesResponse", "LookerExploreReference", "LookerExploreReferences", + "LookerGoldenQuery", "LookerQuery", "Message", "OAuthCredentials", @@ -282,6 +296,8 @@ def _get_version(dependency_name): "SchemaMessage", "SchemaQuery", "SchemaResult", + "SpannerDatabaseReference", + "SpannerReference", "StorageMessage", "StudioDatasourceReference", "StudioDatasourceReferences", diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_chat_service/async_client.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_chat_service/async_client.py index 320434fc8879..1aa9229ba416 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_chat_service/async_client.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_chat_service/async_client.py @@ -334,16 +334,10 @@ async def sample_chat(): client = geminidataanalytics_v1alpha.DataChatServiceAsyncClient() # Initialize request argument(s) - inline_context = geminidataanalytics_v1alpha.Context() - inline_context.datasource_references.bq.table_references.project_id = "project_id_value" - inline_context.datasource_references.bq.table_references.dataset_id = "dataset_id_value" - inline_context.datasource_references.bq.table_references.table_id = "table_id_value" - messages = geminidataanalytics_v1alpha.Message() messages.user_message.text = "text_value" request = geminidataanalytics_v1alpha.ChatRequest( - inline_context=inline_context, parent="parent_value", messages=messages, ) @@ -1027,15 +1021,9 @@ async def sample_query_data(): client = geminidataanalytics_v1alpha.DataChatServiceAsyncClient() # Initialize request argument(s) - context = geminidataanalytics_v1alpha.QueryDataContext() - context.datasource_references.bq.table_references.project_id = "project_id_value" - context.datasource_references.bq.table_references.dataset_id = "dataset_id_value" - context.datasource_references.bq.table_references.table_id = "table_id_value" - request = geminidataanalytics_v1alpha.QueryDataRequest( parent="parent_value", prompt="prompt_value", - context=context, ) # Make the request diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_chat_service/client.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_chat_service/client.py index 048dc05a3b23..0baa4db1c3d4 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_chat_service/client.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/services/data_chat_service/client.py @@ -792,16 +792,10 @@ def sample_chat(): client = geminidataanalytics_v1alpha.DataChatServiceClient() # Initialize request argument(s) - inline_context = geminidataanalytics_v1alpha.Context() - inline_context.datasource_references.bq.table_references.project_id = "project_id_value" - inline_context.datasource_references.bq.table_references.dataset_id = "dataset_id_value" - inline_context.datasource_references.bq.table_references.table_id = "table_id_value" - messages = geminidataanalytics_v1alpha.Message() messages.user_message.text = "text_value" request = geminidataanalytics_v1alpha.ChatRequest( - inline_context=inline_context, parent="parent_value", messages=messages, ) @@ -1470,15 +1464,9 @@ def sample_query_data(): client = geminidataanalytics_v1alpha.DataChatServiceClient() # Initialize request argument(s) - context = geminidataanalytics_v1alpha.QueryDataContext() - context.datasource_references.bq.table_references.project_id = "project_id_value" - context.datasource_references.bq.table_references.dataset_id = "dataset_id_value" - context.datasource_references.bq.table_references.table_id = "table_id_value" - request = geminidataanalytics_v1alpha.QueryDataRequest( parent="parent_value", prompt="prompt_value", - context=context, ) # Make the request diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/__init__.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/__init__.py index 39d490ff93a7..1c0709d8d30f 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/__init__.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/__init__.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from .agent_context import AgentContextReference from .context import ( AnalysisOptions, ChartOptions, @@ -21,6 +22,7 @@ DatasourceOptions, ExampleQuery, GlossaryTerm, + LookerGoldenQuery, LookerQuery, ) from .conversation import ( @@ -80,8 +82,12 @@ UserMessage, ) from .datasource import ( + AlloyDbDatabaseReference, + AlloyDbReference, BigQueryTableReference, BigQueryTableReferences, + CloudSqlDatabaseReference, + CloudSqlReference, DataFilter, DataFilterType, Datasource, @@ -91,11 +97,14 @@ LookerExploreReferences, PrivateLookerInstanceInfo, Schema, + SpannerDatabaseReference, + SpannerReference, StudioDatasourceReference, StudioDatasourceReferences, ) __all__ = ( + "AgentContextReference", "AnalysisOptions", "ChartOptions", "Context", @@ -103,6 +112,7 @@ "DatasourceOptions", "ExampleQuery", "GlossaryTerm", + "LookerGoldenQuery", "LookerQuery", "Conversation", "CreateConversationRequest", @@ -155,8 +165,12 @@ "SystemMessage", "TextMessage", "UserMessage", + "AlloyDbDatabaseReference", + "AlloyDbReference", "BigQueryTableReference", "BigQueryTableReferences", + "CloudSqlDatabaseReference", + "CloudSqlReference", "DataFilter", "Datasource", "DatasourceReferences", @@ -165,6 +179,8 @@ "LookerExploreReferences", "PrivateLookerInstanceInfo", "Schema", + "SpannerDatabaseReference", + "SpannerReference", "StudioDatasourceReference", "StudioDatasourceReferences", "DataFilterType", diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/agent_context.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/agent_context.py new file mode 100644 index 000000000000..70dc991a9cf4 --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/agent_context.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.geminidataanalytics.v1alpha", + manifest={ + "AgentContextReference", + }, +) + + +class AgentContextReference(proto.Message): + r"""Message representing a reference to Agent Context. + + Attributes: + context_set_id (str): + Required. Context set ID to retrieve. + """ + + context_set_id: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/context.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/context.py index 9f3616f393b2..0ec422a29242 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/context.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/context.py @@ -27,6 +27,7 @@ manifest={ "Context", "ExampleQuery", + "LookerGoldenQuery", "LookerQuery", "GlossaryTerm", "ConversationOptions", @@ -62,6 +63,11 @@ class Context(proto.Message): SQL queries and their corresponding natural language queries optionally present. Currently only used for BigQuery data sources. + looker_golden_queries (MutableSequence[google.cloud.geminidataanalytics_v1alpha.types.LookerGoldenQuery]): + Optional. A list of golden queries, providing + examples of relevant and commonly used Looker + queries and their corresponding natural language + queries optionally present. glossary_terms (MutableSequence[google.cloud.geminidataanalytics_v1alpha.types.GlossaryTerm]): Optional. Term definitions (currently, only user authored) @@ -181,6 +187,11 @@ class SchemaPaths(proto.Message): number=5, message="ExampleQuery", ) + looker_golden_queries: MutableSequence["LookerGoldenQuery"] = proto.RepeatedField( + proto.MESSAGE, + number=11, + message="LookerGoldenQuery", + ) glossary_terms: MutableSequence["GlossaryTerm"] = proto.RepeatedField( proto.MESSAGE, number=8, @@ -226,6 +237,32 @@ class ExampleQuery(proto.Message): ) +class LookerGoldenQuery(proto.Message): + r"""A golden query for Looker, including natural language + questions and a corresponding Looker Query. Analogous to + ExampleQuery. + + Attributes: + natural_language_questions (MutableSequence[str]): + Optional. Natural language questions that a + user might ask. For example: "How many orders + were placed last month?". + looker_query (google.cloud.geminidataanalytics_v1alpha.types.LookerQuery): + Optional. The Looker Query corresponding to + the natural language questions. + """ + + natural_language_questions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + looker_query: "LookerQuery" = proto.Field( + proto.MESSAGE, + number=5, + message="LookerQuery", + ) + + class LookerQuery(proto.Message): r"""Looker Query Object `Looker API documentation `__. diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/datasource.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/datasource.py index d9cbef726be8..338cea007637 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/datasource.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1alpha/types/datasource.py @@ -23,6 +23,7 @@ from google.cloud.geminidataanalytics_v1alpha.types import ( credentials as gcg_credentials, ) +from google.cloud.geminidataanalytics_v1alpha.types import agent_context __protobuf__ = proto.module( package="google.cloud.geminidataanalytics.v1alpha", @@ -33,6 +34,12 @@ "BigQueryTableReference", "StudioDatasourceReferences", "StudioDatasourceReference", + "AlloyDbReference", + "AlloyDbDatabaseReference", + "SpannerReference", + "SpannerDatabaseReference", + "CloudSqlReference", + "CloudSqlDatabaseReference", "LookerExploreReferences", "LookerExploreReference", "PrivateLookerInstanceInfo", @@ -82,6 +89,21 @@ class DatasourceReferences(proto.Message): looker (google.cloud.geminidataanalytics_v1alpha.types.LookerExploreReferences): References to Looker Explores. + This field is a member of `oneof`_ ``references``. + alloydb (google.cloud.geminidataanalytics_v1alpha.types.AlloyDbReference): + Reference to an AlloyDB database. Only supported for the + ``QueryData`` method. + + This field is a member of `oneof`_ ``references``. + spanner_reference (google.cloud.geminidataanalytics_v1alpha.types.SpannerReference): + Reference to a Spanner database. Only supported for the + ``QueryData`` method. + + This field is a member of `oneof`_ ``references``. + cloud_sql_reference (google.cloud.geminidataanalytics_v1alpha.types.CloudSqlReference): + Reference to a CloudSql database. Only supported for the + ``QueryData`` method. + This field is a member of `oneof`_ ``references``. """ @@ -103,14 +125,34 @@ class DatasourceReferences(proto.Message): oneof="references", message="LookerExploreReferences", ) + alloydb: "AlloyDbReference" = proto.Field( + proto.MESSAGE, + number=8, + oneof="references", + message="AlloyDbReference", + ) + spanner_reference: "SpannerReference" = proto.Field( + proto.MESSAGE, + number=9, + oneof="references", + message="SpannerReference", + ) + cloud_sql_reference: "CloudSqlReference" = proto.Field( + proto.MESSAGE, + number=10, + oneof="references", + message="CloudSqlReference", + ) class BigQueryTableReferences(proto.Message): - r"""Message representing references to BigQuery tables. + r"""Message representing references to BigQuery tables and property + graphs. At least one of ``table_references`` or + ``property_graph_references`` must be populated. Attributes: table_references (MutableSequence[google.cloud.geminidataanalytics_v1alpha.types.BigQueryTableReference]): - Required. References to BigQuery tables. + Optional. References to BigQuery tables. """ table_references: MutableSequence["BigQueryTableReference"] = proto.RepeatedField( @@ -187,6 +229,255 @@ class StudioDatasourceReference(proto.Message): ) +class AlloyDbReference(proto.Message): + r"""Message representing reference to an AlloyDB database and agent + context. Only supported for the ``QueryData`` method. + + Attributes: + database_reference (google.cloud.geminidataanalytics_v1alpha.types.AlloyDbDatabaseReference): + Required. Singular proto that supports + specifying which database and tables to include. + agent_context_reference (google.cloud.geminidataanalytics_v1alpha.types.AgentContextReference): + Optional. Parameters for retrieving data from + Agent Context. + """ + + database_reference: "AlloyDbDatabaseReference" = proto.Field( + proto.MESSAGE, + number=1, + message="AlloyDbDatabaseReference", + ) + agent_context_reference: agent_context.AgentContextReference = proto.Field( + proto.MESSAGE, + number=3, + message=agent_context.AgentContextReference, + ) + + +class AlloyDbDatabaseReference(proto.Message): + r"""Message representing a reference to a single AlloyDB + database. + + Attributes: + project_id (str): + Required. The project the instance belongs + to. + region (str): + Required. The region of the instance. + cluster_id (str): + Required. The cluster id. + instance_id (str): + Required. The instance id. + database_id (str): + Required. The database id. + table_ids (MutableSequence[str]): + Optional. The table ids. Denotes all tables + if unset. + """ + + project_id: str = proto.Field( + proto.STRING, + number=1, + ) + region: str = proto.Field( + proto.STRING, + number=2, + ) + cluster_id: str = proto.Field( + proto.STRING, + number=3, + ) + instance_id: str = proto.Field( + proto.STRING, + number=4, + ) + database_id: str = proto.Field( + proto.STRING, + number=5, + ) + table_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + + +class SpannerReference(proto.Message): + r"""Message representing reference to a Spanner database and agent + context. Only supported for the ``QueryData`` method. + + Attributes: + database_reference (google.cloud.geminidataanalytics_v1alpha.types.SpannerDatabaseReference): + Required. Singular proto that supports + specifying which database and tables to include. + agent_context_reference (google.cloud.geminidataanalytics_v1alpha.types.AgentContextReference): + Optional. Parameters for retrieving data from + Agent Context. + """ + + database_reference: "SpannerDatabaseReference" = proto.Field( + proto.MESSAGE, + number=1, + message="SpannerDatabaseReference", + ) + agent_context_reference: agent_context.AgentContextReference = proto.Field( + proto.MESSAGE, + number=2, + message=agent_context.AgentContextReference, + ) + + +class SpannerDatabaseReference(proto.Message): + r"""Message representing a reference to a single Spanner + database. + + Attributes: + engine (google.cloud.geminidataanalytics_v1alpha.types.SpannerDatabaseReference.Engine): + Required. The engine of the Spanner instance. + project_id (str): + Required. The project the instance belongs + to. + region (str): + Required. The region of the instance. + instance_id (str): + Required. The instance id. + database_id (str): + Required. The database id. + table_ids (MutableSequence[str]): + Optional. The table ids. Denotes all tables + if unset. + """ + + class Engine(proto.Enum): + r"""The database engine. + + Values: + ENGINE_UNSPECIFIED (0): + Engine is not specified. + GOOGLE_SQL (1): + Google SQL + POSTGRESQL (2): + PostgreSQL + """ + ENGINE_UNSPECIFIED = 0 + GOOGLE_SQL = 1 + POSTGRESQL = 2 + + engine: Engine = proto.Field( + proto.ENUM, + number=6, + enum=Engine, + ) + project_id: str = proto.Field( + proto.STRING, + number=1, + ) + region: str = proto.Field( + proto.STRING, + number=2, + ) + instance_id: str = proto.Field( + proto.STRING, + number=3, + ) + database_id: str = proto.Field( + proto.STRING, + number=4, + ) + table_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + + +class CloudSqlReference(proto.Message): + r"""Message representing reference to a CloudSQL database and agent + context. Only supported for the ``QueryData`` method. + + Attributes: + database_reference (google.cloud.geminidataanalytics_v1alpha.types.CloudSqlDatabaseReference): + Required. Singular proto that supports + specifying which database and tables to include. + agent_context_reference (google.cloud.geminidataanalytics_v1alpha.types.AgentContextReference): + Optional. Parameters for retrieving data from + Agent Context. + """ + + database_reference: "CloudSqlDatabaseReference" = proto.Field( + proto.MESSAGE, + number=1, + message="CloudSqlDatabaseReference", + ) + agent_context_reference: agent_context.AgentContextReference = proto.Field( + proto.MESSAGE, + number=2, + message=agent_context.AgentContextReference, + ) + + +class CloudSqlDatabaseReference(proto.Message): + r"""Message representing a reference to a single CloudSQL + database. + + Attributes: + engine (google.cloud.geminidataanalytics_v1alpha.types.CloudSqlDatabaseReference.Engine): + Required. The engine of the Cloud SQL + instance. + project_id (str): + Required. The project the instance belongs + to. + region (str): + Required. The region of the instance. + instance_id (str): + Required. The instance id. + database_id (str): + Required. The database id. + table_ids (MutableSequence[str]): + Optional. The table ids. Denotes all tables + if unset. + """ + + class Engine(proto.Enum): + r"""The database engine. + + Values: + ENGINE_UNSPECIFIED (0): + Engine is not specified. + POSTGRESQL (1): + PostgreSQL + MYSQL (2): + MySQL + """ + ENGINE_UNSPECIFIED = 0 + POSTGRESQL = 1 + MYSQL = 2 + + engine: Engine = proto.Field( + proto.ENUM, + number=1, + enum=Engine, + ) + project_id: str = proto.Field( + proto.STRING, + number=2, + ) + region: str = proto.Field( + proto.STRING, + number=3, + ) + instance_id: str = proto.Field( + proto.STRING, + number=4, + ) + database_id: str = proto.Field( + proto.STRING, + number=5, + ) + table_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + + class LookerExploreReferences(proto.Message): r"""Message representing references to Looker explores. @@ -316,6 +607,18 @@ class Datasource(proto.Message): looker_explore_reference (google.cloud.geminidataanalytics_v1alpha.types.LookerExploreReference): A reference to a Looker explore. + This field is a member of `oneof`_ ``reference``. + alloy_db_reference (google.cloud.geminidataanalytics_v1alpha.types.AlloyDbReference): + A reference to an AlloyDB database. + + This field is a member of `oneof`_ ``reference``. + spanner_reference (google.cloud.geminidataanalytics_v1alpha.types.SpannerReference): + A reference to a Spanner database. + + This field is a member of `oneof`_ ``reference``. + cloud_sql_reference (google.cloud.geminidataanalytics_v1alpha.types.CloudSqlReference): + A reference to a CloudSQL database. + This field is a member of `oneof`_ ``reference``. schema (google.cloud.geminidataanalytics_v1alpha.types.Schema): Optional. The schema of the datasource. @@ -346,6 +649,24 @@ class Datasource(proto.Message): oneof="reference", message="LookerExploreReference", ) + alloy_db_reference: "AlloyDbReference" = proto.Field( + proto.MESSAGE, + number=12, + oneof="reference", + message="AlloyDbReference", + ) + spanner_reference: "SpannerReference" = proto.Field( + proto.MESSAGE, + number=13, + oneof="reference", + message="SpannerReference", + ) + cloud_sql_reference: "CloudSqlReference" = proto.Field( + proto.MESSAGE, + number=14, + oneof="reference", + message="CloudSqlReference", + ) schema: "Schema" = proto.Field( proto.MESSAGE, number=7, diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/__init__.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/__init__.py index d0bb2480cc82..2b84fb18ed3f 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/__init__.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/__init__.py @@ -36,6 +36,7 @@ DataChatServiceAsyncClient, DataChatServiceClient, ) +from .types.agent_context import AgentContextReference from .types.context import ( AnalysisOptions, ChartOptions, @@ -44,6 +45,8 @@ DatasourceOptions, ExampleQuery, GlossaryTerm, + LookerGoldenQuery, + LookerQuery, ) from .types.conversation import ( Conversation, @@ -85,10 +88,14 @@ DataResult, ErrorMessage, ExampleQueries, + ExecutedQueryResult, + GenerationOptions, ListMessagesRequest, ListMessagesResponse, - LookerQuery, Message, + QueryDataContext, + QueryDataRequest, + QueryDataResponse, SchemaMessage, SchemaQuery, SchemaResult, @@ -98,8 +105,12 @@ UserMessage, ) from .types.datasource import ( + AlloyDbDatabaseReference, + AlloyDbReference, BigQueryTableReference, BigQueryTableReferences, + CloudSqlDatabaseReference, + CloudSqlReference, DataFilter, DataFilterType, Datasource, @@ -109,6 +120,8 @@ LookerExploreReferences, PrivateLookerInstanceInfo, Schema, + SpannerDatabaseReference, + SpannerReference, StudioDatasourceReference, StudioDatasourceReferences, ) @@ -210,6 +223,9 @@ def _get_version(dependency_name): __all__ = ( "DataAgentServiceAsyncClient", "DataChatServiceAsyncClient", + "AgentContextReference", + "AlloyDbDatabaseReference", + "AlloyDbReference", "AnalysisEvent", "AnalysisMessage", "AnalysisOptions", @@ -224,6 +240,8 @@ def _get_version(dependency_name): "ChartResult", "ChatRequest", "ClientManagedResourceContext", + "CloudSqlDatabaseReference", + "CloudSqlReference", "Context", "Conversation", "ConversationOptions", @@ -249,7 +267,9 @@ def _get_version(dependency_name): "ErrorMessage", "ExampleQueries", "ExampleQuery", + "ExecutedQueryResult", "Field", + "GenerationOptions", "GetConversationRequest", "GetDataAgentRequest", "GlossaryTerm", @@ -263,15 +283,21 @@ def _get_version(dependency_name): "ListMessagesResponse", "LookerExploreReference", "LookerExploreReferences", + "LookerGoldenQuery", "LookerQuery", "Message", "OAuthCredentials", "OperationMetadata", "PrivateLookerInstanceInfo", + "QueryDataContext", + "QueryDataRequest", + "QueryDataResponse", "Schema", "SchemaMessage", "SchemaQuery", "SchemaResult", + "SpannerDatabaseReference", + "SpannerReference", "StorageMessage", "StudioDatasourceReference", "StudioDatasourceReferences", diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/gapic_metadata.json b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/gapic_metadata.json index 524e15c03fa1..fa2caecf75ee 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/gapic_metadata.json +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/gapic_metadata.json @@ -178,6 +178,11 @@ "methods": [ "list_messages" ] + }, + "QueryData": { + "methods": [ + "query_data" + ] } } }, @@ -213,6 +218,11 @@ "methods": [ "list_messages" ] + }, + "QueryData": { + "methods": [ + "query_data" + ] } } }, @@ -248,6 +258,11 @@ "methods": [ "list_messages" ] + }, + "QueryData": { + "methods": [ + "query_data" + ] } } } diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/async_client.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/async_client.py index dd7075b1c475..d7612cd9c85e 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/async_client.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/async_client.py @@ -334,16 +334,10 @@ async def sample_chat(): client = geminidataanalytics_v1beta.DataChatServiceAsyncClient() # Initialize request argument(s) - inline_context = geminidataanalytics_v1beta.Context() - inline_context.datasource_references.bq.table_references.project_id = "project_id_value" - inline_context.datasource_references.bq.table_references.dataset_id = "dataset_id_value" - inline_context.datasource_references.bq.table_references.table_id = "table_id_value" - messages = geminidataanalytics_v1beta.Message() messages.user_message.text = "text_value" request = geminidataanalytics_v1beta.ChatRequest( - inline_context=inline_context, parent="parent_value", messages=messages, ) @@ -1001,6 +995,93 @@ async def sample_list_messages(): # Done; return the response. return response + async def query_data( + self, + request: Optional[Union[data_chat_service.QueryDataRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> data_chat_service.QueryDataResponse: + r"""Queries data from a natural language user query. + + .. 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 geminidataanalytics_v1beta + + async def sample_query_data(): + # Create a client + client = geminidataanalytics_v1beta.DataChatServiceAsyncClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1beta.QueryDataRequest( + parent="parent_value", + prompt="prompt_value", + ) + + # Make the request + response = await client.query_data(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.geminidataanalytics_v1beta.types.QueryDataRequest, dict]]): + The request object. Request to query data from a natural + language query. + 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.geminidataanalytics_v1beta.types.QueryDataResponse: + Response containing the generated + query and related information. + + """ + # 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, data_chat_service.QueryDataRequest): + request = data_chat_service.QueryDataRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.query_data + ] + + # 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 list_operations( self, request: Optional[operations_pb2.ListOperationsRequest] = None, diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/client.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/client.py index 576e7f296d0b..d7572def9a4f 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/client.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/client.py @@ -792,16 +792,10 @@ def sample_chat(): client = geminidataanalytics_v1beta.DataChatServiceClient() # Initialize request argument(s) - inline_context = geminidataanalytics_v1beta.Context() - inline_context.datasource_references.bq.table_references.project_id = "project_id_value" - inline_context.datasource_references.bq.table_references.dataset_id = "dataset_id_value" - inline_context.datasource_references.bq.table_references.table_id = "table_id_value" - messages = geminidataanalytics_v1beta.Message() messages.user_message.text = "text_value" request = geminidataanalytics_v1beta.ChatRequest( - inline_context=inline_context, parent="parent_value", messages=messages, ) @@ -1444,6 +1438,91 @@ def sample_list_messages(): # Done; return the response. return response + def query_data( + self, + request: Optional[Union[data_chat_service.QueryDataRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> data_chat_service.QueryDataResponse: + r"""Queries data from a natural language user query. + + .. 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 geminidataanalytics_v1beta + + def sample_query_data(): + # Create a client + client = geminidataanalytics_v1beta.DataChatServiceClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1beta.QueryDataRequest( + parent="parent_value", + prompt="prompt_value", + ) + + # Make the request + response = client.query_data(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.geminidataanalytics_v1beta.types.QueryDataRequest, dict]): + The request object. Request to query data from a natural + language query. + 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.geminidataanalytics_v1beta.types.QueryDataResponse: + Response containing the generated + query and related information. + + """ + # 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, data_chat_service.QueryDataRequest): + request = data_chat_service.QueryDataRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.query_data] + + # 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 __enter__(self) -> "DataChatServiceClient": return self diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/transports/base.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/transports/base.py index 3394f80cdd3c..2577dc685c7b 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/transports/base.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/transports/base.py @@ -170,6 +170,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.query_data: gapic_v1.method.wrap_method( + self.query_data, + default_timeout=None, + client_info=client_info, + ), self.get_location: gapic_v1.method.wrap_method( self.get_location, default_timeout=None, @@ -271,6 +276,18 @@ def list_messages( ]: raise NotImplementedError() + @property + def query_data( + self, + ) -> Callable[ + [data_chat_service.QueryDataRequest], + Union[ + data_chat_service.QueryDataResponse, + Awaitable[data_chat_service.QueryDataResponse], + ], + ]: + raise NotImplementedError() + @property def list_operations( self, diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/transports/grpc.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/transports/grpc.py index d85d84b0d216..8685c6a26e84 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/transports/grpc.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/transports/grpc.py @@ -497,6 +497,34 @@ def list_messages( ) return self._stubs["list_messages"] + @property + def query_data( + self, + ) -> Callable[ + [data_chat_service.QueryDataRequest], data_chat_service.QueryDataResponse + ]: + r"""Return a callable for the query data method over gRPC. + + Queries data from a natural language user query. + + Returns: + Callable[[~.QueryDataRequest], + ~.QueryDataResponse]: + 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 "query_data" not in self._stubs: + self._stubs["query_data"] = self._logged_channel.unary_unary( + "/google.cloud.geminidataanalytics.v1beta.DataChatService/QueryData", + request_serializer=data_chat_service.QueryDataRequest.serialize, + response_deserializer=data_chat_service.QueryDataResponse.deserialize, + ) + return self._stubs["query_data"] + def close(self): self._logged_channel.close() diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/transports/grpc_asyncio.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/transports/grpc_asyncio.py index b1f968a26fa3..09525e524cf5 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/transports/grpc_asyncio.py @@ -512,6 +512,35 @@ def list_messages( ) return self._stubs["list_messages"] + @property + def query_data( + self, + ) -> Callable[ + [data_chat_service.QueryDataRequest], + Awaitable[data_chat_service.QueryDataResponse], + ]: + r"""Return a callable for the query data method over gRPC. + + Queries data from a natural language user query. + + Returns: + Callable[[~.QueryDataRequest], + Awaitable[~.QueryDataResponse]]: + 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 "query_data" not in self._stubs: + self._stubs["query_data"] = self._logged_channel.unary_unary( + "/google.cloud.geminidataanalytics.v1beta.DataChatService/QueryData", + request_serializer=data_chat_service.QueryDataRequest.serialize, + response_deserializer=data_chat_service.QueryDataResponse.deserialize, + ) + return self._stubs["query_data"] + def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { @@ -545,6 +574,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.query_data: self._wrap_method( + self.query_data, + default_timeout=None, + client_info=client_info, + ), self.get_location: self._wrap_method( self.get_location, default_timeout=None, diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/transports/rest.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/transports/rest.py index aaa0549141ba..633c13997f9c 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/transports/rest.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/transports/rest.py @@ -123,6 +123,14 @@ def post_list_messages(self, response): logging.log(f"Received response: {response}") return response + def pre_query_data(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_query_data(self, response): + logging.log(f"Received response: {response}") + return response + transport = DataChatServiceRestTransport(interceptor=MyCustomDataChatServiceInterceptor()) client = DataChatServiceClient(transport=transport) @@ -388,6 +396,56 @@ def post_list_messages_with_metadata( """ return response, metadata + def pre_query_data( + self, + request: data_chat_service.QueryDataRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + data_chat_service.QueryDataRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for query_data + + Override in a subclass to manipulate the request or metadata + before they are sent to the DataChatService server. + """ + return request, metadata + + def post_query_data( + self, response: data_chat_service.QueryDataResponse + ) -> data_chat_service.QueryDataResponse: + """Post-rpc interceptor for query_data + + DEPRECATED. Please use the `post_query_data_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DataChatService server but before + it is returned to user code. This `post_query_data` interceptor runs + before the `post_query_data_with_metadata` interceptor. + """ + return response + + def post_query_data_with_metadata( + self, + response: data_chat_service.QueryDataResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + data_chat_service.QueryDataResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for query_data + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DataChatService server but before it is returned to user code. + + We recommend only using this `post_query_data_with_metadata` + interceptor in new development instead of the `post_query_data` interceptor. + When both interceptors are used, this `post_query_data_with_metadata` interceptor runs after the + `post_query_data` interceptor. The (possibly modified) response returned by + `post_query_data` will be passed to + `post_query_data_with_metadata`. + """ + return response, metadata + def pre_get_location( self, request: locations_pb2.GetLocationRequest, @@ -1478,6 +1536,165 @@ def __call__( ) return resp + class _QueryData( + _BaseDataChatServiceRestTransport._BaseQueryData, DataChatServiceRestStub + ): + def __hash__(self): + return hash("DataChatServiceRestTransport.QueryData") + + @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: data_chat_service.QueryDataRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> data_chat_service.QueryDataResponse: + r"""Call the query data method over HTTP. + + Args: + request (~.data_chat_service.QueryDataRequest): + The request object. Request to query data from a natural + language query. + 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: + ~.data_chat_service.QueryDataResponse: + Response containing the generated + query and related information. + + """ + + http_options = ( + _BaseDataChatServiceRestTransport._BaseQueryData._get_http_options() + ) + + request, metadata = self._interceptor.pre_query_data(request, metadata) + transcoded_request = _BaseDataChatServiceRestTransport._BaseQueryData._get_transcoded_request( + http_options, request + ) + + body = ( + _BaseDataChatServiceRestTransport._BaseQueryData._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseDataChatServiceRestTransport._BaseQueryData._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.geminidataanalytics_v1beta.DataChatServiceClient.QueryData", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1beta.DataChatService", + "rpcName": "QueryData", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DataChatServiceRestTransport._QueryData._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 = data_chat_service.QueryDataResponse() + pb_resp = data_chat_service.QueryDataResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_query_data(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_query_data_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = data_chat_service.QueryDataResponse.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.geminidataanalytics_v1beta.DataChatServiceClient.query_data", + extra={ + "serviceName": "google.cloud.geminidataanalytics.v1beta.DataChatService", + "rpcName": "QueryData", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + @property def chat( self, @@ -1532,6 +1749,16 @@ def list_messages( # In C++ this would require a dynamic_cast return self._ListMessages(self._session, self._host, self._interceptor) # type: ignore + @property + def query_data( + self, + ) -> Callable[ + [data_chat_service.QueryDataRequest], data_chat_service.QueryDataResponse + ]: + # 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._QueryData(self._session, self._host, self._interceptor) # type: ignore + @property def get_location(self): return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/transports/rest_base.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/transports/rest_base.py index 66efa053783a..2f747fb78f91 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/transports/rest_base.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/services/data_chat_service/transports/rest_base.py @@ -396,6 +396,63 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseQueryData: + 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/*}:queryData", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = data_chat_service.QueryDataRequest.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( + _BaseDataChatServiceRestTransport._BaseQueryData._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.") diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/__init__.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/__init__.py index 9d500fc67339..1c0709d8d30f 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/__init__.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/__init__.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from .agent_context import AgentContextReference from .context import ( AnalysisOptions, ChartOptions, @@ -21,6 +22,8 @@ DatasourceOptions, ExampleQuery, GlossaryTerm, + LookerGoldenQuery, + LookerQuery, ) from .conversation import ( Conversation, @@ -62,10 +65,14 @@ DataResult, ErrorMessage, ExampleQueries, + ExecutedQueryResult, + GenerationOptions, ListMessagesRequest, ListMessagesResponse, - LookerQuery, Message, + QueryDataContext, + QueryDataRequest, + QueryDataResponse, SchemaMessage, SchemaQuery, SchemaResult, @@ -75,8 +82,12 @@ UserMessage, ) from .datasource import ( + AlloyDbDatabaseReference, + AlloyDbReference, BigQueryTableReference, BigQueryTableReferences, + CloudSqlDatabaseReference, + CloudSqlReference, DataFilter, DataFilterType, Datasource, @@ -86,11 +97,14 @@ LookerExploreReferences, PrivateLookerInstanceInfo, Schema, + SpannerDatabaseReference, + SpannerReference, StudioDatasourceReference, StudioDatasourceReferences, ) __all__ = ( + "AgentContextReference", "AnalysisOptions", "ChartOptions", "Context", @@ -98,6 +112,8 @@ "DatasourceOptions", "ExampleQuery", "GlossaryTerm", + "LookerGoldenQuery", + "LookerQuery", "Conversation", "CreateConversationRequest", "DeleteConversationRequest", @@ -134,10 +150,14 @@ "DataResult", "ErrorMessage", "ExampleQueries", + "ExecutedQueryResult", + "GenerationOptions", "ListMessagesRequest", "ListMessagesResponse", - "LookerQuery", "Message", + "QueryDataContext", + "QueryDataRequest", + "QueryDataResponse", "SchemaMessage", "SchemaQuery", "SchemaResult", @@ -145,8 +165,12 @@ "SystemMessage", "TextMessage", "UserMessage", + "AlloyDbDatabaseReference", + "AlloyDbReference", "BigQueryTableReference", "BigQueryTableReferences", + "CloudSqlDatabaseReference", + "CloudSqlReference", "DataFilter", "Datasource", "DatasourceReferences", @@ -155,6 +179,8 @@ "LookerExploreReferences", "PrivateLookerInstanceInfo", "Schema", + "SpannerDatabaseReference", + "SpannerReference", "StudioDatasourceReference", "StudioDatasourceReferences", "DataFilterType", diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/agent_context.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/agent_context.py new file mode 100644 index 000000000000..2d30e84990c6 --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/agent_context.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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.geminidataanalytics.v1beta", + manifest={ + "AgentContextReference", + }, +) + + +class AgentContextReference(proto.Message): + r"""Message representing a reference to Agent Context. + + Attributes: + context_set_id (str): + Required. Context set ID to retrieve. + """ + + context_set_id: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/context.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/context.py index d6612de8bb95..0a9ce18d949f 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/context.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/context.py @@ -27,6 +27,8 @@ manifest={ "Context", "ExampleQuery", + "LookerGoldenQuery", + "LookerQuery", "GlossaryTerm", "ConversationOptions", "DatasourceOptions", @@ -61,6 +63,11 @@ class Context(proto.Message): SQL queries and their corresponding natural language queries optionally present. Currently only used for BigQuery data sources. + looker_golden_queries (MutableSequence[google.cloud.geminidataanalytics_v1beta.types.LookerGoldenQuery]): + Optional. A list of golden queries, providing + examples of relevant and commonly used Looker + queries and their corresponding natural language + queries optionally present. glossary_terms (MutableSequence[google.cloud.geminidataanalytics_v1beta.types.GlossaryTerm]): Optional. Term definitions (currently, only user authored) @@ -180,6 +187,11 @@ class SchemaPaths(proto.Message): number=5, message="ExampleQuery", ) + looker_golden_queries: MutableSequence["LookerGoldenQuery"] = proto.RepeatedField( + proto.MESSAGE, + number=11, + message="LookerGoldenQuery", + ) glossary_terms: MutableSequence["GlossaryTerm"] = proto.RepeatedField( proto.MESSAGE, number=8, @@ -225,6 +237,108 @@ class ExampleQuery(proto.Message): ) +class LookerGoldenQuery(proto.Message): + r"""A golden query for Looker, including natural language + questions and a corresponding Looker Query. Analogous to + ExampleQuery. + + Attributes: + natural_language_questions (MutableSequence[str]): + Optional. Natural language questions that a + user might ask. For example: "How many orders + were placed last month?". + looker_query (google.cloud.geminidataanalytics_v1beta.types.LookerQuery): + Optional. The Looker Query corresponding to + the natural language questions. + """ + + natural_language_questions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + looker_query: "LookerQuery" = proto.Field( + proto.MESSAGE, + number=5, + message="LookerQuery", + ) + + +class LookerQuery(proto.Message): + r"""Looker Query Object `Looker API + documentation `__. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + model (str): + Required. The LookML model used to generate + the query. + explore (str): + Required. The LookML explore used to generate + the query. + fields (MutableSequence[str]): + Optional. The fields to retrieve from the + explore. + filters (MutableSequence[google.cloud.geminidataanalytics_v1beta.types.LookerQuery.Filter]): + Optional. The filters to apply to the + explore. + sorts (MutableSequence[str]): + Optional. The sorts to apply to the explore. + limit (str): + Optional. Limit in the query. + + This field is a member of `oneof`_ ``_limit``. + """ + + class Filter(proto.Message): + r"""A Looker query filter. + + Attributes: + field (str): + Required. The field to filter on. + value (str): + Required. The value for the field to filter + on. + """ + + field: str = proto.Field( + proto.STRING, + number=1, + ) + value: str = proto.Field( + proto.STRING, + number=2, + ) + + model: str = proto.Field( + proto.STRING, + number=1, + ) + explore: str = proto.Field( + proto.STRING, + number=2, + ) + fields: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + filters: MutableSequence[Filter] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message=Filter, + ) + sorts: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + limit: str = proto.Field( + proto.STRING, + number=6, + optional=True, + ) + + class GlossaryTerm(proto.Message): r"""Definition of a term within a specific domain. diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/data_chat_service.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/data_chat_service.py index 0393223f14a6..b11efaddbde7 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/data_chat_service.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/data_chat_service.py @@ -21,13 +21,18 @@ from google.protobuf import timestamp_pb2 # type: ignore import proto # type: ignore +from google.cloud.geminidataanalytics_v1beta.types import context as gcg_context from google.cloud.geminidataanalytics_v1beta.types import credentials as gcg_credentials -from google.cloud.geminidataanalytics_v1beta.types import context from google.cloud.geminidataanalytics_v1beta.types import datasource __protobuf__ = proto.module( package="google.cloud.geminidataanalytics.v1beta", manifest={ + "QueryDataRequest", + "GenerationOptions", + "QueryDataContext", + "QueryDataResponse", + "ExecutedQueryResult", "ListMessagesRequest", "ListMessagesResponse", "StorageMessage", @@ -43,7 +48,6 @@ "SchemaQuery", "SchemaResult", "DataMessage", - "LookerQuery", "DataQuery", "DataResult", "BigQueryJob", @@ -60,6 +64,256 @@ ) +class QueryDataRequest(proto.Message): + r"""Request to query data from a natural language query. + + Attributes: + parent (str): + Required. The parent resource to generate the + query for. Format: + projects/{project}/locations/{location} + prompt (str): + Required. The natural language query for + which to generate query. Example: "What are the + top 5 best selling products this month?". + context (google.cloud.geminidataanalytics_v1beta.types.QueryDataContext): + Required. The context for the data query, + including the data sources to use. + generation_options (google.cloud.geminidataanalytics_v1beta.types.GenerationOptions): + Optional. Options to control query generation + and execution behavior. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + prompt: str = proto.Field( + proto.STRING, + number=2, + ) + context: "QueryDataContext" = proto.Field( + proto.MESSAGE, + number=3, + message="QueryDataContext", + ) + generation_options: "GenerationOptions" = proto.Field( + proto.MESSAGE, + number=4, + message="GenerationOptions", + ) + + +class GenerationOptions(proto.Message): + r"""Options to control query generation, execution, and response + format. + + Attributes: + generate_query_result (bool): + Optional. If true, the generated query will + be executed, and the result data will be + returned in the response. + generate_natural_language_answer (bool): + Optional. If true, a natural language answer + based on the query execution result will be + generated and returned in the response. + generate_explanation (bool): + Optional. If true, an explanation of the + generated query will be returned in the + response. + generate_disambiguation_question (bool): + Optional. If true (default to false), the service may return + a clarifying_question if the input query is ambiguous. + """ + + generate_query_result: bool = proto.Field( + proto.BOOL, + number=1, + ) + generate_natural_language_answer: bool = proto.Field( + proto.BOOL, + number=2, + ) + generate_explanation: bool = proto.Field( + proto.BOOL, + number=3, + ) + generate_disambiguation_question: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class QueryDataContext(proto.Message): + r"""References to data sources and context to use for the query. + + Attributes: + datasource_references (google.cloud.geminidataanalytics_v1beta.types.DatasourceReferences): + Required. The datasource references to use + for the query. + """ + + datasource_references: datasource.DatasourceReferences = proto.Field( + proto.MESSAGE, + number=1, + message=datasource.DatasourceReferences, + ) + + +class QueryDataResponse(proto.Message): + r"""Response containing the generated query and related + information. + + Attributes: + generated_query (str): + Generated query for the given user prompt. + intent_explanation (str): + A natural language explanation of the generated query. + Populated if options.generate_explanation was true in the + request. + query_result (google.cloud.geminidataanalytics_v1beta.types.ExecutedQueryResult): + The result of executing the query. Populated if + options.generate_query_result or + options.generate_natural_language_answer was true in the + request, and execution was successful or attempted. + natural_language_answer (str): + A natural language answer to the query, based on the + query_result. Populated if + options.generate_natural_language_answer was true in the + request and query execution was successful based in the + response from executeSql API. + disambiguation_question (MutableSequence[str]): + If ambiguity was detected in the natural language query and + options.generate_disambiguation_question was true, this + field contains a question to the user for clarification. The + returned represents the service's best effort based on the + ambiguous input. + """ + + generated_query: str = proto.Field( + proto.STRING, + number=1, + ) + intent_explanation: str = proto.Field( + proto.STRING, + number=2, + ) + query_result: "ExecutedQueryResult" = proto.Field( + proto.MESSAGE, + number=3, + message="ExecutedQueryResult", + ) + natural_language_answer: str = proto.Field( + proto.STRING, + number=4, + ) + disambiguation_question: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + + +class ExecutedQueryResult(proto.Message): + r"""The result of a query execution. The design is generic for + all dialects. + + Attributes: + columns (MutableSequence[google.cloud.geminidataanalytics_v1beta.types.ExecutedQueryResult.Column]): + The columns in the result set, in order. + rows (MutableSequence[google.cloud.geminidataanalytics_v1beta.types.ExecutedQueryResult.Row]): + The rows returned by the query. + total_row_count (int): + The total number of rows in the full result + set, if known. This may be an estimate or an + exact count. + partial_result (bool): + Set to true if the returned rows in ``query_result`` are a + subset of the full result. This can happen, for example, if + the query execution hits a row limit. When true, the + ``query_result`` does not contain all rows. To retrieve the + complete result, consider using the ``generated_query`` in + ``QueryDataResponse`` and executing it in your own + environment. + query_execution_error (str): + The error message if the query execution + failed. + """ + + class Column(proto.Message): + r"""Describes a single column in the result set. + + Attributes: + name (str): + The name of the column. + type_ (str): + The type of the column (e.g., "VARCHAR", + "INT64", "TIMESTAMP"). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + type_: str = proto.Field( + proto.STRING, + number=2, + ) + + class Value(proto.Message): + r"""Represents a single value within a row. + + Attributes: + value (str): + The cell value, represented in a string + format. Timestamps could be formatted, for + example, using RFC3339Nano. This field is used + if the value is not null. + """ + + value: str = proto.Field( + proto.STRING, + number=1, + ) + + class Row(proto.Message): + r"""Represents a single row in the result set. + + Attributes: + values (MutableSequence[google.cloud.geminidataanalytics_v1beta.types.ExecutedQueryResult.Value]): + The values in the row, corresponding + positionally to the columns. + """ + + values: MutableSequence["ExecutedQueryResult.Value"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="ExecutedQueryResult.Value", + ) + + columns: MutableSequence[Column] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=Column, + ) + rows: MutableSequence[Row] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=Row, + ) + total_row_count: int = proto.Field( + proto.INT64, + number=3, + ) + partial_result: bool = proto.Field( + proto.BOOL, + number=4, + ) + query_execution_error: str = proto.Field( + proto.STRING, + number=5, + ) + + class ListMessagesRequest(proto.Message): r"""Request for listing chat messages based on parent and conversation_id. @@ -202,11 +456,11 @@ class ChatRequest(proto.Message): Required. Content of current conversation. """ - inline_context: context.Context = proto.Field( + inline_context: gcg_context.Context = proto.Field( proto.MESSAGE, number=101, oneof="context_provider", - message=context.Context, + message=gcg_context.Context, ) conversation_reference: "ConversationReference" = proto.Field( proto.MESSAGE, @@ -336,10 +590,10 @@ class ClientManagedResourceContext(proto.Message): Optional. The client managed agent id. """ - inline_context: context.Context = proto.Field( + inline_context: gcg_context.Context = proto.Field( proto.MESSAGE, number=1, - message=context.Context, + message=gcg_context.Context, ) conversation_id: str = proto.Field( proto.STRING, @@ -691,11 +945,11 @@ class DataMessage(proto.Message): oneof="kind", message="DataResult", ) - generated_looker_query: "LookerQuery" = proto.Field( + generated_looker_query: gcg_context.LookerQuery = proto.Field( proto.MESSAGE, number=4, oneof="kind", - message="LookerQuery", + message=gcg_context.LookerQuery, ) big_query_job: "BigQueryJob" = proto.Field( proto.MESSAGE, @@ -705,81 +959,6 @@ class DataMessage(proto.Message): ) -class LookerQuery(proto.Message): - r"""A query for retrieving data from a Looker Explore. See `Run Inline - Query `__. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - model (str): - Required. The LookML model used to generate - the query. - explore (str): - Required. The LookML Explore used to generate - the query. - fields (MutableSequence[str]): - Optional. The fields to retrieve from the - Explore. - filters (MutableSequence[google.cloud.geminidataanalytics_v1beta.types.LookerQuery.Filter]): - Optional. The filters to apply to the - Explore. - sorts (MutableSequence[str]): - Optional. The sorts to apply to the Explore. - limit (str): - Optional. Limit in the query. - - This field is a member of `oneof`_ ``_limit``. - """ - - class Filter(proto.Message): - r"""A Looker query filter. - - Attributes: - field (str): - Required. The field to filter on. - value (str): - Required. The value f field to filter on. - """ - - field: str = proto.Field( - proto.STRING, - number=1, - ) - value: str = proto.Field( - proto.STRING, - number=2, - ) - - model: str = proto.Field( - proto.STRING, - number=1, - ) - explore: str = proto.Field( - proto.STRING, - number=2, - ) - fields: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - filters: MutableSequence[Filter] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message=Filter, - ) - sorts: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - limit: str = proto.Field( - proto.STRING, - number=6, - optional=True, - ) - - class DataQuery(proto.Message): r"""A query for retrieving data. @@ -806,11 +985,11 @@ class DataQuery(proto.Message): the question. """ - looker: "LookerQuery" = proto.Field( + looker: gcg_context.LookerQuery = proto.Field( proto.MESSAGE, number=4, oneof="query_type", - message="LookerQuery", + message=gcg_context.LookerQuery, ) question: str = proto.Field( proto.STRING, @@ -1205,10 +1384,10 @@ class ExampleQueries(proto.Message): BigQuery data sources. """ - example_queries: MutableSequence[context.ExampleQuery] = proto.RepeatedField( + example_queries: MutableSequence[gcg_context.ExampleQuery] = proto.RepeatedField( proto.MESSAGE, number=1, - message=context.ExampleQuery, + message=gcg_context.ExampleQuery, ) diff --git a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/datasource.py b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/datasource.py index 10099c65f190..be46f73303fa 100644 --- a/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/datasource.py +++ b/packages/google-cloud-geminidataanalytics/google/cloud/geminidataanalytics_v1beta/types/datasource.py @@ -21,6 +21,7 @@ import proto # type: ignore from google.cloud.geminidataanalytics_v1beta.types import credentials as gcg_credentials +from google.cloud.geminidataanalytics_v1beta.types import agent_context __protobuf__ = proto.module( package="google.cloud.geminidataanalytics.v1beta", @@ -31,6 +32,12 @@ "BigQueryTableReference", "StudioDatasourceReferences", "StudioDatasourceReference", + "AlloyDbReference", + "AlloyDbDatabaseReference", + "SpannerReference", + "SpannerDatabaseReference", + "CloudSqlReference", + "CloudSqlDatabaseReference", "LookerExploreReferences", "LookerExploreReference", "PrivateLookerInstanceInfo", @@ -80,6 +87,21 @@ class DatasourceReferences(proto.Message): looker (google.cloud.geminidataanalytics_v1beta.types.LookerExploreReferences): References to Looker Explores. + This field is a member of `oneof`_ ``references``. + alloydb (google.cloud.geminidataanalytics_v1beta.types.AlloyDbReference): + Reference to an AlloyDB database. Only supported for the + ``QueryData`` method. + + This field is a member of `oneof`_ ``references``. + spanner_reference (google.cloud.geminidataanalytics_v1beta.types.SpannerReference): + Reference to a Spanner database. Only supported for the + ``QueryData`` method. + + This field is a member of `oneof`_ ``references``. + cloud_sql_reference (google.cloud.geminidataanalytics_v1beta.types.CloudSqlReference): + Reference to a CloudSql database. Only supported for the + ``QueryData`` method. + This field is a member of `oneof`_ ``references``. """ @@ -101,14 +123,34 @@ class DatasourceReferences(proto.Message): oneof="references", message="LookerExploreReferences", ) + alloydb: "AlloyDbReference" = proto.Field( + proto.MESSAGE, + number=8, + oneof="references", + message="AlloyDbReference", + ) + spanner_reference: "SpannerReference" = proto.Field( + proto.MESSAGE, + number=9, + oneof="references", + message="SpannerReference", + ) + cloud_sql_reference: "CloudSqlReference" = proto.Field( + proto.MESSAGE, + number=10, + oneof="references", + message="CloudSqlReference", + ) class BigQueryTableReferences(proto.Message): - r"""Message representing references to BigQuery tables. + r"""Message representing references to BigQuery tables and property + graphs. At least one of ``table_references`` or + ``property_graph_references`` must be populated. Attributes: table_references (MutableSequence[google.cloud.geminidataanalytics_v1beta.types.BigQueryTableReference]): - Required. References to BigQuery tables. + Optional. References to BigQuery tables. """ table_references: MutableSequence["BigQueryTableReference"] = proto.RepeatedField( @@ -185,6 +227,255 @@ class StudioDatasourceReference(proto.Message): ) +class AlloyDbReference(proto.Message): + r"""Message representing reference to an AlloyDB database and agent + context. Only supported for the ``QueryData`` method. + + Attributes: + database_reference (google.cloud.geminidataanalytics_v1beta.types.AlloyDbDatabaseReference): + Required. Singular proto that supports + specifying which database and tables to include. + agent_context_reference (google.cloud.geminidataanalytics_v1beta.types.AgentContextReference): + Optional. Parameters for retrieving data from + Agent Context. + """ + + database_reference: "AlloyDbDatabaseReference" = proto.Field( + proto.MESSAGE, + number=1, + message="AlloyDbDatabaseReference", + ) + agent_context_reference: agent_context.AgentContextReference = proto.Field( + proto.MESSAGE, + number=3, + message=agent_context.AgentContextReference, + ) + + +class AlloyDbDatabaseReference(proto.Message): + r"""Message representing a reference to a single AlloyDB + database. + + Attributes: + project_id (str): + Required. The project the instance belongs + to. + region (str): + Required. The region of the instance. + cluster_id (str): + Required. The cluster id. + instance_id (str): + Required. The instance id. + database_id (str): + Required. The database id. + table_ids (MutableSequence[str]): + Optional. The table ids. Denotes all tables + if unset. + """ + + project_id: str = proto.Field( + proto.STRING, + number=1, + ) + region: str = proto.Field( + proto.STRING, + number=2, + ) + cluster_id: str = proto.Field( + proto.STRING, + number=3, + ) + instance_id: str = proto.Field( + proto.STRING, + number=4, + ) + database_id: str = proto.Field( + proto.STRING, + number=5, + ) + table_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=6, + ) + + +class SpannerReference(proto.Message): + r"""Message representing reference to a Spanner database and agent + context. Only supported for the ``QueryData`` method. + + Attributes: + database_reference (google.cloud.geminidataanalytics_v1beta.types.SpannerDatabaseReference): + Required. Singular proto that supports + specifying which database and tables to include. + agent_context_reference (google.cloud.geminidataanalytics_v1beta.types.AgentContextReference): + Optional. Parameters for retrieving data from + Agent Context. + """ + + database_reference: "SpannerDatabaseReference" = proto.Field( + proto.MESSAGE, + number=1, + message="SpannerDatabaseReference", + ) + agent_context_reference: agent_context.AgentContextReference = proto.Field( + proto.MESSAGE, + number=2, + message=agent_context.AgentContextReference, + ) + + +class SpannerDatabaseReference(proto.Message): + r"""Message representing a reference to a single Spanner + database. + + Attributes: + engine (google.cloud.geminidataanalytics_v1beta.types.SpannerDatabaseReference.Engine): + Required. The engine of the Spanner instance. + project_id (str): + Required. The project the instance belongs + to. + region (str): + Required. The region of the instance. + instance_id (str): + Required. The instance id. + database_id (str): + Required. The database id. + table_ids (MutableSequence[str]): + Optional. The table ids. Denotes all tables + if unset. + """ + + class Engine(proto.Enum): + r"""The database engine. + + Values: + ENGINE_UNSPECIFIED (0): + Engine is not specified. + GOOGLE_SQL (1): + Google SQL + POSTGRESQL (2): + PostgreSQL + """ + ENGINE_UNSPECIFIED = 0 + GOOGLE_SQL = 1 + POSTGRESQL = 2 + + engine: Engine = proto.Field( + proto.ENUM, + number=6, + enum=Engine, + ) + project_id: str = proto.Field( + proto.STRING, + number=1, + ) + region: str = proto.Field( + proto.STRING, + number=2, + ) + instance_id: str = proto.Field( + proto.STRING, + number=3, + ) + database_id: str = proto.Field( + proto.STRING, + number=4, + ) + table_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + + +class CloudSqlReference(proto.Message): + r"""Message representing reference to a CloudSQL database and agent + context. Only supported for the ``QueryData`` method. + + Attributes: + database_reference (google.cloud.geminidataanalytics_v1beta.types.CloudSqlDatabaseReference): + Required. Singular proto that supports + specifying which database and tables to include. + agent_context_reference (google.cloud.geminidataanalytics_v1beta.types.AgentContextReference): + Optional. Parameters for retrieving data from + Agent Context. + """ + + database_reference: "CloudSqlDatabaseReference" = proto.Field( + proto.MESSAGE, + number=1, + message="CloudSqlDatabaseReference", + ) + agent_context_reference: agent_context.AgentContextReference = proto.Field( + proto.MESSAGE, + number=2, + message=agent_context.AgentContextReference, + ) + + +class CloudSqlDatabaseReference(proto.Message): + r"""Message representing a reference to a single CloudSQL + database. + + Attributes: + engine (google.cloud.geminidataanalytics_v1beta.types.CloudSqlDatabaseReference.Engine): + Required. The engine of the Cloud SQL + instance. + project_id (str): + Required. The project the instance belongs + to. + region (str): + Required. The region of the instance. + instance_id (str): + Required. The instance id. + database_id (str): + Required. The database id. + table_ids (MutableSequence[str]): + Optional. The table ids. Denotes all tables + if unset. + """ + + class Engine(proto.Enum): + r"""The database engine. + + Values: + ENGINE_UNSPECIFIED (0): + Engine is not specified. + POSTGRESQL (1): + PostgreSQL + MYSQL (2): + MySQL + """ + ENGINE_UNSPECIFIED = 0 + POSTGRESQL = 1 + MYSQL = 2 + + engine: Engine = proto.Field( + proto.ENUM, + number=1, + enum=Engine, + ) + project_id: str = proto.Field( + proto.STRING, + number=2, + ) + region: str = proto.Field( + proto.STRING, + number=3, + ) + instance_id: str = proto.Field( + proto.STRING, + number=4, + ) + database_id: str = proto.Field( + proto.STRING, + number=5, + ) + table_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + + class LookerExploreReferences(proto.Message): r"""Message representing references to Looker explores. @@ -314,6 +605,18 @@ class Datasource(proto.Message): looker_explore_reference (google.cloud.geminidataanalytics_v1beta.types.LookerExploreReference): A reference to a Looker explore. + This field is a member of `oneof`_ ``reference``. + alloy_db_reference (google.cloud.geminidataanalytics_v1beta.types.AlloyDbReference): + A reference to an AlloyDB database. + + This field is a member of `oneof`_ ``reference``. + spanner_reference (google.cloud.geminidataanalytics_v1beta.types.SpannerReference): + A reference to a Spanner database. + + This field is a member of `oneof`_ ``reference``. + cloud_sql_reference (google.cloud.geminidataanalytics_v1beta.types.CloudSqlReference): + A reference to a CloudSQL database. + This field is a member of `oneof`_ ``reference``. schema (google.cloud.geminidataanalytics_v1beta.types.Schema): Optional. The schema of the datasource. @@ -344,6 +647,24 @@ class Datasource(proto.Message): oneof="reference", message="LookerExploreReference", ) + alloy_db_reference: "AlloyDbReference" = proto.Field( + proto.MESSAGE, + number=12, + oneof="reference", + message="AlloyDbReference", + ) + spanner_reference: "SpannerReference" = proto.Field( + proto.MESSAGE, + number=13, + oneof="reference", + message="SpannerReference", + ) + cloud_sql_reference: "CloudSqlReference" = proto.Field( + proto.MESSAGE, + number=14, + oneof="reference", + message="CloudSqlReference", + ) schema: "Schema" = proto.Field( proto.MESSAGE, number=7, diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_chat_service_chat_async.py b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_chat_service_chat_async.py index 0fd279f19f84..2d2585b563f0 100644 --- a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_chat_service_chat_async.py +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_chat_service_chat_async.py @@ -39,20 +39,10 @@ async def sample_chat(): client = geminidataanalytics_v1alpha.DataChatServiceAsyncClient() # Initialize request argument(s) - inline_context = geminidataanalytics_v1alpha.Context() - inline_context.datasource_references.bq.table_references.project_id = ( - "project_id_value" - ) - inline_context.datasource_references.bq.table_references.dataset_id = ( - "dataset_id_value" - ) - inline_context.datasource_references.bq.table_references.table_id = "table_id_value" - messages = geminidataanalytics_v1alpha.Message() messages.user_message.text = "text_value" request = geminidataanalytics_v1alpha.ChatRequest( - inline_context=inline_context, parent="parent_value", messages=messages, ) diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_chat_service_chat_sync.py b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_chat_service_chat_sync.py index ebc33e517e25..23864e4f054e 100644 --- a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_chat_service_chat_sync.py +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_chat_service_chat_sync.py @@ -39,20 +39,10 @@ def sample_chat(): client = geminidataanalytics_v1alpha.DataChatServiceClient() # Initialize request argument(s) - inline_context = geminidataanalytics_v1alpha.Context() - inline_context.datasource_references.bq.table_references.project_id = ( - "project_id_value" - ) - inline_context.datasource_references.bq.table_references.dataset_id = ( - "dataset_id_value" - ) - inline_context.datasource_references.bq.table_references.table_id = "table_id_value" - messages = geminidataanalytics_v1alpha.Message() messages.user_message.text = "text_value" request = geminidataanalytics_v1alpha.ChatRequest( - inline_context=inline_context, parent="parent_value", messages=messages, ) diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_chat_service_query_data_async.py b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_chat_service_query_data_async.py index efbb17642a40..f59179f01746 100644 --- a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_chat_service_query_data_async.py +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_chat_service_query_data_async.py @@ -39,15 +39,9 @@ async def sample_query_data(): client = geminidataanalytics_v1alpha.DataChatServiceAsyncClient() # Initialize request argument(s) - context = geminidataanalytics_v1alpha.QueryDataContext() - context.datasource_references.bq.table_references.project_id = "project_id_value" - context.datasource_references.bq.table_references.dataset_id = "dataset_id_value" - context.datasource_references.bq.table_references.table_id = "table_id_value" - request = geminidataanalytics_v1alpha.QueryDataRequest( parent="parent_value", prompt="prompt_value", - context=context, ) # Make the request diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_chat_service_query_data_sync.py b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_chat_service_query_data_sync.py index ab03b1f33376..f127cef16858 100644 --- a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_chat_service_query_data_sync.py +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1alpha_generated_data_chat_service_query_data_sync.py @@ -39,15 +39,9 @@ def sample_query_data(): client = geminidataanalytics_v1alpha.DataChatServiceClient() # Initialize request argument(s) - context = geminidataanalytics_v1alpha.QueryDataContext() - context.datasource_references.bq.table_references.project_id = "project_id_value" - context.datasource_references.bq.table_references.dataset_id = "dataset_id_value" - context.datasource_references.bq.table_references.table_id = "table_id_value" - request = geminidataanalytics_v1alpha.QueryDataRequest( parent="parent_value", prompt="prompt_value", - context=context, ) # Make the request diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_chat_service_chat_async.py b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_chat_service_chat_async.py index 622a2afd20f0..db2bbf7150cb 100644 --- a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_chat_service_chat_async.py +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_chat_service_chat_async.py @@ -39,20 +39,10 @@ async def sample_chat(): client = geminidataanalytics_v1beta.DataChatServiceAsyncClient() # Initialize request argument(s) - inline_context = geminidataanalytics_v1beta.Context() - inline_context.datasource_references.bq.table_references.project_id = ( - "project_id_value" - ) - inline_context.datasource_references.bq.table_references.dataset_id = ( - "dataset_id_value" - ) - inline_context.datasource_references.bq.table_references.table_id = "table_id_value" - messages = geminidataanalytics_v1beta.Message() messages.user_message.text = "text_value" request = geminidataanalytics_v1beta.ChatRequest( - inline_context=inline_context, parent="parent_value", messages=messages, ) diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_chat_service_chat_sync.py b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_chat_service_chat_sync.py index f07db485b3f8..d29de7f9b2f5 100644 --- a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_chat_service_chat_sync.py +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_chat_service_chat_sync.py @@ -39,20 +39,10 @@ def sample_chat(): client = geminidataanalytics_v1beta.DataChatServiceClient() # Initialize request argument(s) - inline_context = geminidataanalytics_v1beta.Context() - inline_context.datasource_references.bq.table_references.project_id = ( - "project_id_value" - ) - inline_context.datasource_references.bq.table_references.dataset_id = ( - "dataset_id_value" - ) - inline_context.datasource_references.bq.table_references.table_id = "table_id_value" - messages = geminidataanalytics_v1beta.Message() messages.user_message.text = "text_value" request = geminidataanalytics_v1beta.ChatRequest( - inline_context=inline_context, parent="parent_value", messages=messages, ) diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_chat_service_query_data_async.py b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_chat_service_query_data_async.py new file mode 100644 index 000000000000..e307e379a802 --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_chat_service_query_data_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 QueryData +# 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-geminidataanalytics + + +# [START geminidataanalytics_v1beta_generated_DataChatService_QueryData_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 geminidataanalytics_v1beta + + +async def sample_query_data(): + # Create a client + client = geminidataanalytics_v1beta.DataChatServiceAsyncClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1beta.QueryDataRequest( + parent="parent_value", + prompt="prompt_value", + ) + + # Make the request + response = await client.query_data(request=request) + + # Handle the response + print(response) + + +# [END geminidataanalytics_v1beta_generated_DataChatService_QueryData_async] diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_chat_service_query_data_sync.py b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_chat_service_query_data_sync.py new file mode 100644 index 000000000000..0b353314f7bc --- /dev/null +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/geminidataanalytics_v1beta_generated_data_chat_service_query_data_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 QueryData +# 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-geminidataanalytics + + +# [START geminidataanalytics_v1beta_generated_DataChatService_QueryData_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 geminidataanalytics_v1beta + + +def sample_query_data(): + # Create a client + client = geminidataanalytics_v1beta.DataChatServiceClient() + + # Initialize request argument(s) + request = geminidataanalytics_v1beta.QueryDataRequest( + parent="parent_value", + prompt="prompt_value", + ) + + # Make the request + response = client.query_data(request=request) + + # Handle the response + print(response) + + +# [END geminidataanalytics_v1beta_generated_DataChatService_QueryData_sync] diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/snippet_metadata_google.cloud.geminidataanalytics.v1alpha.json b/packages/google-cloud-geminidataanalytics/samples/generated_samples/snippet_metadata_google.cloud.geminidataanalytics.v1alpha.json index 120ab1b74d04..44c5aa336cb7 100644 --- a/packages/google-cloud-geminidataanalytics/samples/generated_samples/snippet_metadata_google.cloud.geminidataanalytics.v1alpha.json +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/snippet_metadata_google.cloud.geminidataanalytics.v1alpha.json @@ -1368,12 +1368,12 @@ "regionTag": "geminidataanalytics_v1alpha_generated_DataChatService_Chat_async", "segments": [ { - "end": 62, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 62, + "end": 56, "start": 27, "type": "SHORT" }, @@ -1383,18 +1383,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 55, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 58, - "start": 56, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 63, - "start": 59, + "end": 57, + "start": 53, "type": "RESPONSE_HANDLING" } ], @@ -1444,12 +1444,12 @@ "regionTag": "geminidataanalytics_v1alpha_generated_DataChatService_Chat_sync", "segments": [ { - "end": 62, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 62, + "end": 56, "start": 27, "type": "SHORT" }, @@ -1459,18 +1459,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 55, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 58, - "start": 56, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 63, - "start": 59, + "end": 57, + "start": 53, "type": "RESPONSE_HANDLING" } ], @@ -2336,12 +2336,12 @@ "regionTag": "geminidataanalytics_v1alpha_generated_DataChatService_QueryData_async", "segments": [ { - "end": 58, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 58, + "end": 52, "start": 27, "type": "SHORT" }, @@ -2351,18 +2351,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 52, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 55, - "start": 53, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 59, - "start": 56, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], @@ -2412,12 +2412,12 @@ "regionTag": "geminidataanalytics_v1alpha_generated_DataChatService_QueryData_sync", "segments": [ { - "end": 58, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 58, + "end": 52, "start": 27, "type": "SHORT" }, @@ -2427,18 +2427,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 52, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 55, - "start": 53, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 59, - "start": 56, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], diff --git a/packages/google-cloud-geminidataanalytics/samples/generated_samples/snippet_metadata_google.cloud.geminidataanalytics.v1beta.json b/packages/google-cloud-geminidataanalytics/samples/generated_samples/snippet_metadata_google.cloud.geminidataanalytics.v1beta.json index 310fffe7aff1..d4b2cb9ed852 100644 --- a/packages/google-cloud-geminidataanalytics/samples/generated_samples/snippet_metadata_google.cloud.geminidataanalytics.v1beta.json +++ b/packages/google-cloud-geminidataanalytics/samples/generated_samples/snippet_metadata_google.cloud.geminidataanalytics.v1beta.json @@ -1368,12 +1368,12 @@ "regionTag": "geminidataanalytics_v1beta_generated_DataChatService_Chat_async", "segments": [ { - "end": 62, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 62, + "end": 56, "start": 27, "type": "SHORT" }, @@ -1383,18 +1383,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 55, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 58, - "start": 56, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 63, - "start": 59, + "end": 57, + "start": 53, "type": "RESPONSE_HANDLING" } ], @@ -1444,12 +1444,12 @@ "regionTag": "geminidataanalytics_v1beta_generated_DataChatService_Chat_sync", "segments": [ { - "end": 62, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 62, + "end": 56, "start": 27, "type": "SHORT" }, @@ -1459,18 +1459,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 55, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 58, - "start": 56, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 63, - "start": 59, + "end": 57, + "start": 53, "type": "RESPONSE_HANDLING" } ], @@ -2290,6 +2290,159 @@ } ], "title": "geminidataanalytics_v1beta_generated_data_chat_service_list_messages_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.geminidataanalytics_v1beta.DataChatServiceAsyncClient", + "shortName": "DataChatServiceAsyncClient" + }, + "fullName": "google.cloud.geminidataanalytics_v1beta.DataChatServiceAsyncClient.query_data", + "method": { + "fullName": "google.cloud.geminidataanalytics.v1beta.DataChatService.QueryData", + "service": { + "fullName": "google.cloud.geminidataanalytics.v1beta.DataChatService", + "shortName": "DataChatService" + }, + "shortName": "QueryData" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.geminidataanalytics_v1beta.types.QueryDataRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.geminidataanalytics_v1beta.types.QueryDataResponse", + "shortName": "query_data" + }, + "description": "Sample for QueryData", + "file": "geminidataanalytics_v1beta_generated_data_chat_service_query_data_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "geminidataanalytics_v1beta_generated_DataChatService_QueryData_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": "geminidataanalytics_v1beta_generated_data_chat_service_query_data_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.geminidataanalytics_v1beta.DataChatServiceClient", + "shortName": "DataChatServiceClient" + }, + "fullName": "google.cloud.geminidataanalytics_v1beta.DataChatServiceClient.query_data", + "method": { + "fullName": "google.cloud.geminidataanalytics.v1beta.DataChatService.QueryData", + "service": { + "fullName": "google.cloud.geminidataanalytics.v1beta.DataChatService", + "shortName": "DataChatService" + }, + "shortName": "QueryData" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.geminidataanalytics_v1beta.types.QueryDataRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.geminidataanalytics_v1beta.types.QueryDataResponse", + "shortName": "query_data" + }, + "description": "Sample for QueryData", + "file": "geminidataanalytics_v1beta_generated_data_chat_service_query_data_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "geminidataanalytics_v1beta_generated_DataChatService_QueryData_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": "geminidataanalytics_v1beta_generated_data_chat_service_query_data_sync.py" } ] } diff --git a/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1alpha/test_data_agent_service.py b/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1alpha/test_data_agent_service.py index f63b76644ad6..15f9f05f9307 100644 --- a/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1alpha/test_data_agent_service.py +++ b/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1alpha/test_data_agent_service.py @@ -82,8 +82,12 @@ data_analytics_agent, datasource, ) +from google.cloud.geminidataanalytics_v1alpha.types import ( + agent_context, + context, + credentials, +) from google.cloud.geminidataanalytics_v1alpha.types import data_agent as gcg_data_agent -from google.cloud.geminidataanalytics_v1alpha.types import context, credentials from google.cloud.geminidataanalytics_v1alpha.types import data_agent CRED_INFO_JSON = { @@ -7319,6 +7323,41 @@ def test_create_data_agent_rest_call_success(request_type): } }, }, + "alloydb": { + "database_reference": { + "project_id": "project_id_value", + "region": "region_value", + "cluster_id": "cluster_id_value", + "instance_id": "instance_id_value", + "database_id": "database_id_value", + "table_ids": ["table_ids_value1", "table_ids_value2"], + }, + "agent_context_reference": { + "context_set_id": "context_set_id_value" + }, + }, + "spanner_reference": { + "database_reference": { + "engine": 1, + "project_id": "project_id_value", + "region": "region_value", + "instance_id": "instance_id_value", + "database_id": "database_id_value", + "table_ids": ["table_ids_value1", "table_ids_value2"], + }, + "agent_context_reference": {}, + }, + "cloud_sql_reference": { + "database_reference": { + "engine": 1, + "project_id": "project_id_value", + "region": "region_value", + "instance_id": "instance_id_value", + "database_id": "database_id_value", + "table_ids": ["table_ids_value1", "table_ids_value2"], + }, + "agent_context_reference": {}, + }, }, "options": { "chart": {"image": {"no_image": {}, "svg": {}}}, @@ -7331,6 +7370,24 @@ def test_create_data_agent_rest_call_success(request_type): "natural_language_question": "natural_language_question_value", } ], + "looker_golden_queries": [ + { + "natural_language_questions": [ + "natural_language_questions_value1", + "natural_language_questions_value2", + ], + "looker_query": { + "model": "model_value", + "explore": "explore_value", + "fields": ["fields_value1", "fields_value2"], + "filters": [ + {"field": "field_value", "value": "value_value"} + ], + "sorts": ["sorts_value1", "sorts_value2"], + "limit": "limit_value", + }, + } + ], "glossary_terms": [ { "display_name": "display_name_value", @@ -7627,6 +7684,41 @@ def test_update_data_agent_rest_call_success(request_type): } }, }, + "alloydb": { + "database_reference": { + "project_id": "project_id_value", + "region": "region_value", + "cluster_id": "cluster_id_value", + "instance_id": "instance_id_value", + "database_id": "database_id_value", + "table_ids": ["table_ids_value1", "table_ids_value2"], + }, + "agent_context_reference": { + "context_set_id": "context_set_id_value" + }, + }, + "spanner_reference": { + "database_reference": { + "engine": 1, + "project_id": "project_id_value", + "region": "region_value", + "instance_id": "instance_id_value", + "database_id": "database_id_value", + "table_ids": ["table_ids_value1", "table_ids_value2"], + }, + "agent_context_reference": {}, + }, + "cloud_sql_reference": { + "database_reference": { + "engine": 1, + "project_id": "project_id_value", + "region": "region_value", + "instance_id": "instance_id_value", + "database_id": "database_id_value", + "table_ids": ["table_ids_value1", "table_ids_value2"], + }, + "agent_context_reference": {}, + }, }, "options": { "chart": {"image": {"no_image": {}, "svg": {}}}, @@ -7639,6 +7731,24 @@ def test_update_data_agent_rest_call_success(request_type): "natural_language_question": "natural_language_question_value", } ], + "looker_golden_queries": [ + { + "natural_language_questions": [ + "natural_language_questions_value1", + "natural_language_questions_value2", + ], + "looker_query": { + "model": "model_value", + "explore": "explore_value", + "fields": ["fields_value1", "fields_value2"], + "filters": [ + {"field": "field_value", "value": "value_value"} + ], + "sorts": ["sorts_value1", "sorts_value2"], + "limit": "limit_value", + }, + } + ], "glossary_terms": [ { "display_name": "display_name_value", diff --git a/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1alpha/test_data_chat_service.py b/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1alpha/test_data_chat_service.py index 437036a80c39..c1e48ff2e7a4 100644 --- a/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1alpha/test_data_chat_service.py +++ b/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1alpha/test_data_chat_service.py @@ -63,6 +63,7 @@ pagers, transports, ) +from google.cloud.geminidataanalytics_v1alpha.types import agent_context, context from google.cloud.geminidataanalytics_v1alpha.types import ( credentials, data_chat_service, @@ -71,7 +72,6 @@ from google.cloud.geminidataanalytics_v1alpha.types import ( conversation as gcg_conversation, ) -from google.cloud.geminidataanalytics_v1alpha.types import context from google.cloud.geminidataanalytics_v1alpha.types import conversation CRED_INFO_JSON = { diff --git a/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1beta/test_data_agent_service.py b/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1beta/test_data_agent_service.py index df49f0bbd97b..14d317413d95 100644 --- a/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1beta/test_data_agent_service.py +++ b/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1beta/test_data_agent_service.py @@ -82,8 +82,12 @@ data_analytics_agent, datasource, ) +from google.cloud.geminidataanalytics_v1beta.types import ( + agent_context, + context, + credentials, +) from google.cloud.geminidataanalytics_v1beta.types import data_agent as gcg_data_agent -from google.cloud.geminidataanalytics_v1beta.types import context, credentials from google.cloud.geminidataanalytics_v1beta.types import data_agent CRED_INFO_JSON = { @@ -7319,6 +7323,41 @@ def test_create_data_agent_rest_call_success(request_type): } }, }, + "alloydb": { + "database_reference": { + "project_id": "project_id_value", + "region": "region_value", + "cluster_id": "cluster_id_value", + "instance_id": "instance_id_value", + "database_id": "database_id_value", + "table_ids": ["table_ids_value1", "table_ids_value2"], + }, + "agent_context_reference": { + "context_set_id": "context_set_id_value" + }, + }, + "spanner_reference": { + "database_reference": { + "engine": 1, + "project_id": "project_id_value", + "region": "region_value", + "instance_id": "instance_id_value", + "database_id": "database_id_value", + "table_ids": ["table_ids_value1", "table_ids_value2"], + }, + "agent_context_reference": {}, + }, + "cloud_sql_reference": { + "database_reference": { + "engine": 1, + "project_id": "project_id_value", + "region": "region_value", + "instance_id": "instance_id_value", + "database_id": "database_id_value", + "table_ids": ["table_ids_value1", "table_ids_value2"], + }, + "agent_context_reference": {}, + }, }, "options": { "chart": {"image": {"no_image": {}, "svg": {}}}, @@ -7331,6 +7370,24 @@ def test_create_data_agent_rest_call_success(request_type): "natural_language_question": "natural_language_question_value", } ], + "looker_golden_queries": [ + { + "natural_language_questions": [ + "natural_language_questions_value1", + "natural_language_questions_value2", + ], + "looker_query": { + "model": "model_value", + "explore": "explore_value", + "fields": ["fields_value1", "fields_value2"], + "filters": [ + {"field": "field_value", "value": "value_value"} + ], + "sorts": ["sorts_value1", "sorts_value2"], + "limit": "limit_value", + }, + } + ], "glossary_terms": [ { "display_name": "display_name_value", @@ -7627,6 +7684,41 @@ def test_update_data_agent_rest_call_success(request_type): } }, }, + "alloydb": { + "database_reference": { + "project_id": "project_id_value", + "region": "region_value", + "cluster_id": "cluster_id_value", + "instance_id": "instance_id_value", + "database_id": "database_id_value", + "table_ids": ["table_ids_value1", "table_ids_value2"], + }, + "agent_context_reference": { + "context_set_id": "context_set_id_value" + }, + }, + "spanner_reference": { + "database_reference": { + "engine": 1, + "project_id": "project_id_value", + "region": "region_value", + "instance_id": "instance_id_value", + "database_id": "database_id_value", + "table_ids": ["table_ids_value1", "table_ids_value2"], + }, + "agent_context_reference": {}, + }, + "cloud_sql_reference": { + "database_reference": { + "engine": 1, + "project_id": "project_id_value", + "region": "region_value", + "instance_id": "instance_id_value", + "database_id": "database_id_value", + "table_ids": ["table_ids_value1", "table_ids_value2"], + }, + "agent_context_reference": {}, + }, }, "options": { "chart": {"image": {"no_image": {}, "svg": {}}}, @@ -7639,6 +7731,24 @@ def test_update_data_agent_rest_call_success(request_type): "natural_language_question": "natural_language_question_value", } ], + "looker_golden_queries": [ + { + "natural_language_questions": [ + "natural_language_questions_value1", + "natural_language_questions_value2", + ], + "looker_query": { + "model": "model_value", + "explore": "explore_value", + "fields": ["fields_value1", "fields_value2"], + "filters": [ + {"field": "field_value", "value": "value_value"} + ], + "sorts": ["sorts_value1", "sorts_value2"], + "limit": "limit_value", + }, + } + ], "glossary_terms": [ { "display_name": "display_name_value", diff --git a/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1beta/test_data_chat_service.py b/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1beta/test_data_chat_service.py index 14887e0ed7f7..df04f1537a94 100644 --- a/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1beta/test_data_chat_service.py +++ b/packages/google-cloud-geminidataanalytics/tests/unit/gapic/geminidataanalytics_v1beta/test_data_chat_service.py @@ -63,6 +63,7 @@ pagers, transports, ) +from google.cloud.geminidataanalytics_v1beta.types import agent_context, context from google.cloud.geminidataanalytics_v1beta.types import ( credentials, data_chat_service, @@ -71,7 +72,6 @@ from google.cloud.geminidataanalytics_v1beta.types import ( conversation as gcg_conversation, ) -from google.cloud.geminidataanalytics_v1beta.types import context from google.cloud.geminidataanalytics_v1beta.types import conversation CRED_INFO_JSON = { @@ -3676,6 +3676,259 @@ async def test_list_messages_async_pages(): assert page_.raw_page.next_page_token == token +@pytest.mark.parametrize( + "request_type", + [ + data_chat_service.QueryDataRequest, + dict, + ], +) +def test_query_data(request_type, transport: str = "grpc"): + client = DataChatServiceClient( + 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.query_data), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = data_chat_service.QueryDataResponse( + generated_query="generated_query_value", + intent_explanation="intent_explanation_value", + natural_language_answer="natural_language_answer_value", + disambiguation_question=["disambiguation_question_value"], + ) + response = client.query_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = data_chat_service.QueryDataRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, data_chat_service.QueryDataResponse) + assert response.generated_query == "generated_query_value" + assert response.intent_explanation == "intent_explanation_value" + assert response.natural_language_answer == "natural_language_answer_value" + assert response.disambiguation_question == ["disambiguation_question_value"] + + +def test_query_data_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 = DataChatServiceClient( + 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 = data_chat_service.QueryDataRequest( + parent="parent_value", + prompt="prompt_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.query_data), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.query_data(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == data_chat_service.QueryDataRequest( + parent="parent_value", + prompt="prompt_value", + ) + + +def test_query_data_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 = DataChatServiceClient( + 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.query_data 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.query_data] = mock_rpc + request = {} + client.query_data(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.query_data(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_query_data_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 = DataChatServiceAsyncClient( + 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.query_data + 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.query_data + ] = mock_rpc + + request = {} + await client.query_data(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.query_data(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_query_data_async( + transport: str = "grpc_asyncio", request_type=data_chat_service.QueryDataRequest +): + client = DataChatServiceAsyncClient( + 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.query_data), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + data_chat_service.QueryDataResponse( + generated_query="generated_query_value", + intent_explanation="intent_explanation_value", + natural_language_answer="natural_language_answer_value", + disambiguation_question=["disambiguation_question_value"], + ) + ) + response = await client.query_data(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = data_chat_service.QueryDataRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, data_chat_service.QueryDataResponse) + assert response.generated_query == "generated_query_value" + assert response.intent_explanation == "intent_explanation_value" + assert response.natural_language_answer == "natural_language_answer_value" + assert response.disambiguation_question == ["disambiguation_question_value"] + + +@pytest.mark.asyncio +async def test_query_data_async_from_dict(): + await test_query_data_async(request_type=dict) + + +def test_query_data_field_headers(): + client = DataChatServiceClient( + 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 = data_chat_service.QueryDataRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.query_data), "__call__") as call: + call.return_value = data_chat_service.QueryDataResponse() + client.query_data(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_query_data_field_headers_async(): + client = DataChatServiceAsyncClient( + 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 = data_chat_service.QueryDataRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.query_data), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + data_chat_service.QueryDataResponse() + ) + await client.query_data(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_chat_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -4898,6 +5151,140 @@ def test_list_messages_rest_pager(transport: str = "rest"): assert page_.raw_page.next_page_token == token +def test_query_data_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 = DataChatServiceClient( + 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.query_data 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.query_data] = mock_rpc + + request = {} + client.query_data(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.query_data(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_query_data_rest_required_fields( + request_type=data_chat_service.QueryDataRequest, +): + transport_class = transports.DataChatServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["prompt"] = "" + 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() + ).query_data._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["prompt"] = "prompt_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).query_data._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 "prompt" in jsonified_request + assert jsonified_request["prompt"] == "prompt_value" + + client = DataChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = data_chat_service.QueryDataResponse() + # 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 = data_chat_service.QueryDataResponse.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.query_data(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_query_data_rest_unset_required_fields(): + transport = transports.DataChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.query_data._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "prompt", + "context", + ) + ) + ) + + def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.DataChatServiceGrpcTransport( @@ -5136,6 +5523,27 @@ def test_list_messages_empty_call_grpc(): 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_query_data_empty_call_grpc(): + client = DataChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.query_data), "__call__") as call: + call.return_value = data_chat_service.QueryDataResponse() + client.query_data(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_chat_service.QueryDataRequest() + + assert args[0] == request_msg + + def test_transport_kind_grpc_asyncio(): transport = DataChatServiceAsyncClient.get_transport_class("grpc_asyncio")( credentials=async_anonymous_credentials() @@ -5315,6 +5723,36 @@ async def test_list_messages_empty_call_grpc_asyncio(): 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_query_data_empty_call_grpc_asyncio(): + client = DataChatServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.query_data), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + data_chat_service.QueryDataResponse( + generated_query="generated_query_value", + intent_explanation="intent_explanation_value", + natural_language_answer="natural_language_answer_value", + disambiguation_question=["disambiguation_question_value"], + ) + ) + await client.query_data(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_chat_service.QueryDataRequest() + + assert args[0] == request_msg + + def test_transport_kind_rest(): transport = DataChatServiceClient.get_transport_class("rest")( credentials=ga_credentials.AnonymousCredentials() @@ -6162,6 +6600,142 @@ def test_list_messages_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() +def test_query_data_rest_bad_request(request_type=data_chat_service.QueryDataRequest): + client = DataChatServiceClient( + 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.query_data(request) + + +@pytest.mark.parametrize( + "request_type", + [ + data_chat_service.QueryDataRequest, + dict, + ], +) +def test_query_data_rest_call_success(request_type): + client = DataChatServiceClient( + 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 = data_chat_service.QueryDataResponse( + generated_query="generated_query_value", + intent_explanation="intent_explanation_value", + natural_language_answer="natural_language_answer_value", + disambiguation_question=["disambiguation_question_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 = data_chat_service.QueryDataResponse.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.query_data(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, data_chat_service.QueryDataResponse) + assert response.generated_query == "generated_query_value" + assert response.intent_explanation == "intent_explanation_value" + assert response.natural_language_answer == "natural_language_answer_value" + assert response.disambiguation_question == ["disambiguation_question_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_query_data_rest_interceptors(null_interceptor): + transport = transports.DataChatServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DataChatServiceRestInterceptor(), + ) + client = DataChatServiceClient(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.DataChatServiceRestInterceptor, "post_query_data" + ) as post, mock.patch.object( + transports.DataChatServiceRestInterceptor, "post_query_data_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.DataChatServiceRestInterceptor, "pre_query_data" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = data_chat_service.QueryDataRequest.pb( + data_chat_service.QueryDataRequest() + ) + 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 = data_chat_service.QueryDataResponse.to_json( + data_chat_service.QueryDataResponse() + ) + req.return_value.content = return_value + + request = data_chat_service.QueryDataRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = data_chat_service.QueryDataResponse() + post_with_metadata.return_value = ( + data_chat_service.QueryDataResponse(), + metadata, + ) + + client.query_data( + 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 = DataChatServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6663,6 +7237,26 @@ def test_list_messages_empty_call_rest(): 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_query_data_empty_call_rest(): + client = DataChatServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.query_data), "__call__") as call: + client.query_data(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = data_chat_service.QueryDataRequest() + + assert args[0] == request_msg + + def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = DataChatServiceClient( @@ -6702,6 +7296,7 @@ def test_data_chat_service_base_transport(): "get_conversation", "list_conversations", "list_messages", + "query_data", "get_location", "list_locations", "get_operation", @@ -6984,6 +7579,9 @@ def test_data_chat_service_client_transport_session_collision(transport_name): session1 = client1.transport.list_messages._session session2 = client2.transport.list_messages._session assert session1 != session2 + session1 = client1.transport.query_data._session + session2 = client2.transport.query_data._session + assert session1 != session2 def test_data_chat_service_grpc_transport_channel(): diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore/__init__.py b/packages/google-cloud-memorystore/google/cloud/memorystore/__init__.py index bd032607fbd8..01d91d45776b 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore/__init__.py +++ b/packages/google-cloud-memorystore/google/cloud/memorystore/__init__.py @@ -32,6 +32,7 @@ DeleteBackupRequest, DeleteInstanceRequest, DiscoveryEndpoint, + EncryptionInfo, ExportBackupRequest, GetBackupCollectionRequest, GetBackupRequest, @@ -72,6 +73,7 @@ "DeleteBackupRequest", "DeleteInstanceRequest", "DiscoveryEndpoint", + "EncryptionInfo", "ExportBackupRequest", "GetBackupCollectionRequest", "GetBackupRequest", diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/__init__.py b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/__init__.py index 8536908cda28..80838d2d333e 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/__init__.py +++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/__init__.py @@ -42,6 +42,7 @@ DeleteBackupRequest, DeleteInstanceRequest, DiscoveryEndpoint, + EncryptionInfo, ExportBackupRequest, GetBackupCollectionRequest, GetBackupRequest, @@ -176,6 +177,7 @@ def _get_version(dependency_name): "DeleteBackupRequest", "DeleteInstanceRequest", "DiscoveryEndpoint", + "EncryptionInfo", "ExportBackupRequest", "GetBackupCollectionRequest", "GetBackupRequest", diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/client.py b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/client.py index 2b86aba2b484..3d22fb6c40da 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/client.py +++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/services/memorystore/client.py @@ -318,6 +318,32 @@ def parse_crypto_key_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def crypto_key_version_path( + project: str, + location: str, + key_ring: str, + crypto_key: str, + crypto_key_version: str, + ) -> str: + """Returns a fully-qualified crypto_key_version string.""" + return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}".format( + project=project, + location=location, + key_ring=key_ring, + crypto_key=crypto_key, + crypto_key_version=crypto_key_version, + ) + + @staticmethod + def parse_crypto_key_version_path(path: str) -> Dict[str, str]: + """Parses a crypto_key_version path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)/cryptoKeyVersions/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def forwarding_rule_path( project: str, diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/types/__init__.py b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/types/__init__.py index fd36d368bd79..2886a362b990 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/types/__init__.py +++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/types/__init__.py @@ -26,6 +26,7 @@ DeleteBackupRequest, DeleteInstanceRequest, DiscoveryEndpoint, + EncryptionInfo, ExportBackupRequest, GetBackupCollectionRequest, GetBackupRequest, @@ -65,6 +66,7 @@ "DeleteBackupRequest", "DeleteInstanceRequest", "DiscoveryEndpoint", + "EncryptionInfo", "ExportBackupRequest", "GetBackupCollectionRequest", "GetBackupRequest", diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/types/memorystore.py b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/types/memorystore.py index edb2bb8827a8..7b68815bbac0 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1/types/memorystore.py +++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1/types/memorystore.py @@ -64,6 +64,7 @@ "GetCertificateAuthorityRequest", "CertificateAuthority", "OperationMetadata", + "EncryptionInfo", }, ) @@ -165,9 +166,13 @@ class Instance(proto.Message): shard_count (int): Optional. Number of shards for the instance. discovery_endpoints (MutableSequence[google.cloud.memorystore_v1.types.DiscoveryEndpoint]): - Output only. Deprecated: Use the - endpoints.connections.psc_auto_connection or - endpoints.connections.psc_connection values instead. + Output only. Deprecated: The discovery_endpoints parameter + is deprecated. As a result, it will not be populated if the + connections are created using endpoints parameter. Instead + of this parameter, for discovery, use + endpoints.connections.pscConnection and + endpoints.connections.pscAutoConnection with connectionType + CONNECTION_TYPE_DISCOVERY. node_type (google.cloud.memorystore_v1.types.Instance.NodeType): Optional. Machine type for individual nodes of the instance. @@ -201,11 +206,26 @@ class Instance(proto.Message): Optional. Endpoints for the instance. mode (google.cloud.memorystore_v1.types.Instance.Mode): Optional. The mode config for the instance. + simulate_maintenance_event (bool): + Optional. Input only. Simulate a maintenance + event. + + This field is a member of `oneof`_ ``_simulate_maintenance_event``. ondemand_maintenance (bool): Optional. Input only. Ondemand maintenance for the instance. This field is a member of `oneof`_ ``_ondemand_maintenance``. + satisfies_pzs (bool): + Optional. Output only. Reserved for future + use. + + This field is a member of `oneof`_ ``_satisfies_pzs``. + satisfies_pzi (bool): + Optional. Output only. Reserved for future + use. + + This field is a member of `oneof`_ ``_satisfies_pzi``. maintenance_policy (google.cloud.memorystore_v1.types.MaintenancePolicy): Optional. The maintenance policy for the instance. If not provided, the maintenance event @@ -225,6 +245,14 @@ class Instance(proto.Message): are deleted. This field is a member of `oneof`_ ``_async_instance_endpoints_deletion_enabled``. + kms_key (str): + Optional. The KMS key used to encrypt the + at-rest data of the cluster. + + This field is a member of `oneof`_ ``_kms_key``. + encryption_info (google.cloud.memorystore_v1.types.EncryptionInfo): + Output only. Encryption information of the + data at rest of the cluster. backup_collection (str): Output only. The backup collection full resource name. Example: @@ -234,6 +262,24 @@ class Instance(proto.Message): automated_backup_config (google.cloud.memorystore_v1.types.AutomatedBackupConfig): Optional. The automated backup config for the instance. + maintenance_version (str): + Optional. This field can be used to trigger self service + update to indicate the desired maintenance version. The + input to this field can be determined by the + available_maintenance_versions field. + + This field is a member of `oneof`_ ``_maintenance_version``. + effective_maintenance_version (str): + Output only. This field represents the actual + maintenance version of the instance. + + This field is a member of `oneof`_ ``_effective_maintenance_version``. + available_maintenance_versions (MutableSequence[str]): + Output only. This field is used to determine + the available maintenance versions for the self + service update. + allow_fewer_zones_deployment (bool): + Optional. Immutable. Deprecated, do not use. """ class State(proto.Enum): @@ -616,11 +662,26 @@ class ConnectionDetail(proto.Message): number=26, enum=Mode, ) + simulate_maintenance_event: bool = proto.Field( + proto.BOOL, + number=27, + optional=True, + ) ondemand_maintenance: bool = proto.Field( proto.BOOL, number=28, optional=True, ) + satisfies_pzs: bool = proto.Field( + proto.BOOL, + number=29, + optional=True, + ) + satisfies_pzi: bool = proto.Field( + proto.BOOL, + number=30, + optional=True, + ) maintenance_policy: "MaintenancePolicy" = proto.Field( proto.MESSAGE, number=31, @@ -641,6 +702,16 @@ class ConnectionDetail(proto.Message): number=44, optional=True, ) + kms_key: str = proto.Field( + proto.STRING, + number=45, + optional=True, + ) + encryption_info: "EncryptionInfo" = proto.Field( + proto.MESSAGE, + number=46, + message="EncryptionInfo", + ) backup_collection: str = proto.Field( proto.STRING, number=47, @@ -651,6 +722,24 @@ class ConnectionDetail(proto.Message): number=48, message="AutomatedBackupConfig", ) + maintenance_version: str = proto.Field( + proto.STRING, + number=49, + optional=True, + ) + effective_maintenance_version: str = proto.Field( + proto.STRING, + number=50, + optional=True, + ) + available_maintenance_versions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=51, + ) + allow_fewer_zones_deployment: bool = proto.Field( + proto.BOOL, + number=54, + ) class AutomatedBackupConfig(proto.Message): @@ -751,6 +840,15 @@ class BackupCollection(proto.Message): create_time (google.protobuf.timestamp_pb2.Timestamp): Output only. The time when the backup collection was created. + total_backup_size_bytes (int): + Output only. Total size of all backups in the + backup collection. + total_backup_count (int): + Output only. Total number of backups in the + backup collection. + last_backup_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The last time a backup was + created in the backup collection. """ name: str = proto.Field( @@ -778,6 +876,19 @@ class BackupCollection(proto.Message): number=7, message=timestamp_pb2.Timestamp, ) + total_backup_size_bytes: int = proto.Field( + proto.INT64, + number=8, + ) + total_backup_count: int = proto.Field( + proto.INT64, + number=10, + ) + last_backup_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=11, + message=timestamp_pb2.Timestamp, + ) class Backup(proto.Message): @@ -821,6 +932,9 @@ class Backup(proto.Message): Output only. Type of the backup. state (google.cloud.memorystore_v1.types.Backup.State): Output only. State of the backup. + encryption_info (google.cloud.memorystore_v1.types.EncryptionInfo): + Output only. Encryption information of the + backup. uid (str): Output only. System assigned unique identifier of the backup. @@ -922,6 +1036,11 @@ class State(proto.Enum): number=13, enum=State, ) + encryption_info: "EncryptionInfo" = proto.Field( + proto.MESSAGE, + number=14, + message="EncryptionInfo", + ) uid: str = proto.Field( proto.STRING, number=15, @@ -2297,4 +2416,99 @@ class OperationMetadata(proto.Message): ) +class EncryptionInfo(proto.Message): + r"""EncryptionInfo describes the encryption information of a + cluster. + + Attributes: + encryption_type (google.cloud.memorystore_v1.types.EncryptionInfo.Type): + Output only. Type of encryption. + kms_key_versions (MutableSequence[str]): + Output only. KMS key versions that are being + used to protect the data at-rest. + kms_key_primary_state (google.cloud.memorystore_v1.types.EncryptionInfo.KmsKeyState): + Output only. The state of the primary version + of the KMS key perceived by the system. This + field is not populated in backups. + last_update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The most recent time when the + encryption info was updated. + """ + + class Type(proto.Enum): + r"""Possible encryption types. + + Values: + TYPE_UNSPECIFIED (0): + Encryption type not specified. Defaults to + GOOGLE_DEFAULT_ENCRYPTION. + GOOGLE_DEFAULT_ENCRYPTION (1): + The data is encrypted at rest with a key that + is fully managed by Google. No key version will + be populated. This is the default state. + CUSTOMER_MANAGED_ENCRYPTION (2): + The data is encrypted at rest with a key that + is managed by the customer. KMS key versions + will be populated. + """ + TYPE_UNSPECIFIED = 0 + GOOGLE_DEFAULT_ENCRYPTION = 1 + CUSTOMER_MANAGED_ENCRYPTION = 2 + + class KmsKeyState(proto.Enum): + r"""The state of the KMS key perceived by the system. Refer to + the public documentation for the impact of each state. + + Values: + KMS_KEY_STATE_UNSPECIFIED (0): + The default value. This value is unused. + ENABLED (1): + The KMS key is enabled and correctly + configured. + PERMISSION_DENIED (2): + Permission denied on the KMS key. + DISABLED (3): + The KMS key is disabled. + DESTROYED (4): + The KMS key is destroyed. + DESTROY_SCHEDULED (5): + The KMS key is scheduled to be destroyed. + EKM_KEY_UNREACHABLE_DETECTED (6): + The EKM key is unreachable. + BILLING_DISABLED (7): + Billing is disabled for the project. + UNKNOWN_FAILURE (8): + All other unknown failures. + """ + KMS_KEY_STATE_UNSPECIFIED = 0 + ENABLED = 1 + PERMISSION_DENIED = 2 + DISABLED = 3 + DESTROYED = 4 + DESTROY_SCHEDULED = 5 + EKM_KEY_UNREACHABLE_DETECTED = 6 + BILLING_DISABLED = 7 + UNKNOWN_FAILURE = 8 + + encryption_type: Type = proto.Field( + proto.ENUM, + number=1, + enum=Type, + ) + kms_key_versions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + kms_key_primary_state: KmsKeyState = proto.Field( + proto.ENUM, + number=3, + enum=KmsKeyState, + ) + last_update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-memorystore/tests/unit/gapic/memorystore_v1/test_memorystore.py b/packages/google-cloud-memorystore/tests/unit/gapic/memorystore_v1/test_memorystore.py index 14af56833212..799a8e7d0a50 100644 --- a/packages/google-cloud-memorystore/tests/unit/gapic/memorystore_v1/test_memorystore.py +++ b/packages/google-cloud-memorystore/tests/unit/gapic/memorystore_v1/test_memorystore.py @@ -4176,9 +4176,17 @@ def test_get_instance_rest_call_success(request_type): engine_version="engine_version_value", deletion_protection_enabled=True, mode=memorystore.Instance.Mode.STANDALONE, + simulate_maintenance_event=True, ondemand_maintenance=True, + satisfies_pzs=True, + satisfies_pzi=True, async_instance_endpoints_deletion_enabled=True, + kms_key="kms_key_value", backup_collection="backup_collection_value", + maintenance_version="maintenance_version_value", + effective_maintenance_version="effective_maintenance_version_value", + available_maintenance_versions=["available_maintenance_versions_value"], + allow_fewer_zones_deployment=True, ) # Wrap the value into a proper Response obj @@ -4212,9 +4220,21 @@ def test_get_instance_rest_call_success(request_type): assert response.engine_version == "engine_version_value" assert response.deletion_protection_enabled is True assert response.mode == memorystore.Instance.Mode.STANDALONE + assert response.simulate_maintenance_event is True assert response.ondemand_maintenance is True + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True assert response.async_instance_endpoints_deletion_enabled is True + assert response.kms_key == "kms_key_value" assert response.backup_collection == "backup_collection_value" + assert response.maintenance_version == "maintenance_version_value" + assert ( + response.effective_maintenance_version == "effective_maintenance_version_value" + ) + assert response.available_maintenance_versions == [ + "available_maintenance_versions_value" + ] + assert response.allow_fewer_zones_deployment is True @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -4388,7 +4408,10 @@ def test_create_instance_rest_call_success(request_type): } ], "mode": 1, + "simulate_maintenance_event": True, "ondemand_maintenance": True, + "satisfies_pzs": True, + "satisfies_pzi": True, "maintenance_policy": { "create_time": {}, "update_time": {}, @@ -4413,12 +4436,26 @@ def test_create_instance_rest_call_success(request_type): "membership": {"primary_instance": {}, "secondary_instances": {}}, }, "async_instance_endpoints_deletion_enabled": True, + "kms_key": "kms_key_value", + "encryption_info": { + "encryption_type": 1, + "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], + "kms_key_primary_state": 1, + "last_update_time": {}, + }, "backup_collection": "backup_collection_value", "automated_backup_config": { "fixed_frequency_schedule": {"start_time": {}}, "automated_backup_mode": 1, "retention": {"seconds": 751, "nanos": 543}, }, + "maintenance_version": "maintenance_version_value", + "effective_maintenance_version": "effective_maintenance_version_value", + "available_maintenance_versions": [ + "available_maintenance_versions_value1", + "available_maintenance_versions_value2", + ], + "allow_fewer_zones_deployment": 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 @@ -4686,7 +4723,10 @@ def test_update_instance_rest_call_success(request_type): } ], "mode": 1, + "simulate_maintenance_event": True, "ondemand_maintenance": True, + "satisfies_pzs": True, + "satisfies_pzi": True, "maintenance_policy": { "create_time": {}, "update_time": {}, @@ -4711,12 +4751,26 @@ def test_update_instance_rest_call_success(request_type): "membership": {"primary_instance": {}, "secondary_instances": {}}, }, "async_instance_endpoints_deletion_enabled": True, + "kms_key": "kms_key_value", + "encryption_info": { + "encryption_type": 1, + "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], + "kms_key_primary_state": 1, + "last_update_time": {}, + }, "backup_collection": "backup_collection_value", "automated_backup_config": { "fixed_frequency_schedule": {"start_time": {}}, "automated_backup_mode": 1, "retention": {"seconds": 751, "nanos": 543}, }, + "maintenance_version": "maintenance_version_value", + "effective_maintenance_version": "effective_maintenance_version_value", + "available_maintenance_versions": [ + "available_maintenance_versions_value1", + "available_maintenance_versions_value2", + ], + "allow_fewer_zones_deployment": 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 @@ -5435,6 +5489,8 @@ def test_get_backup_collection_rest_call_success(request_type): instance="instance_value", kms_key="kms_key_value", uid="uid_value", + total_backup_size_bytes=2457, + total_backup_count=1921, ) # Wrap the value into a proper Response obj @@ -5456,6 +5512,8 @@ def test_get_backup_collection_rest_call_success(request_type): assert response.instance == "instance_value" assert response.kms_key == "kms_key_value" assert response.uid == "uid_value" + assert response.total_backup_size_bytes == 2457 + assert response.total_backup_count == 1921 @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -7188,10 +7246,44 @@ def test_parse_crypto_key_path(): assert expected == actual -def test_forwarding_rule_path(): +def test_crypto_key_version_path(): project = "oyster" - region = "nudibranch" - forwarding_rule = "cuttlefish" + location = "nudibranch" + key_ring = "cuttlefish" + crypto_key = "mussel" + crypto_key_version = "winkle" + expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}".format( + project=project, + location=location, + key_ring=key_ring, + crypto_key=crypto_key, + crypto_key_version=crypto_key_version, + ) + actual = MemorystoreClient.crypto_key_version_path( + project, location, key_ring, crypto_key, crypto_key_version + ) + assert expected == actual + + +def test_parse_crypto_key_version_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "key_ring": "abalone", + "crypto_key": "squid", + "crypto_key_version": "clam", + } + path = MemorystoreClient.crypto_key_version_path(**expected) + + # Check that the path construction is reversible. + actual = MemorystoreClient.parse_crypto_key_version_path(path) + assert expected == actual + + +def test_forwarding_rule_path(): + project = "whelk" + region = "octopus" + forwarding_rule = "oyster" expected = ( "projects/{project}/regions/{region}/forwardingRules/{forwarding_rule}".format( project=project, @@ -7205,9 +7297,9 @@ def test_forwarding_rule_path(): def test_parse_forwarding_rule_path(): expected = { - "project": "mussel", - "region": "winkle", - "forwarding_rule": "nautilus", + "project": "nudibranch", + "region": "cuttlefish", + "forwarding_rule": "mussel", } path = MemorystoreClient.forwarding_rule_path(**expected) @@ -7217,9 +7309,9 @@ def test_parse_forwarding_rule_path(): def test_instance_path(): - project = "scallop" - location = "abalone" - instance = "squid" + project = "winkle" + location = "nautilus" + instance = "scallop" expected = "projects/{project}/locations/{location}/instances/{instance}".format( project=project, location=location, @@ -7231,9 +7323,9 @@ def test_instance_path(): def test_parse_instance_path(): expected = { - "project": "clam", - "location": "whelk", - "instance": "octopus", + "project": "abalone", + "location": "squid", + "instance": "clam", } path = MemorystoreClient.instance_path(**expected) @@ -7243,8 +7335,8 @@ def test_parse_instance_path(): def test_network_path(): - project = "oyster" - network = "nudibranch" + project = "whelk" + network = "octopus" expected = "projects/{project}/global/networks/{network}".format( project=project, network=network, @@ -7255,8 +7347,8 @@ def test_network_path(): def test_parse_network_path(): expected = { - "project": "cuttlefish", - "network": "mussel", + "project": "oyster", + "network": "nudibranch", } path = MemorystoreClient.network_path(**expected) @@ -7266,9 +7358,9 @@ def test_parse_network_path(): def test_service_attachment_path(): - project = "winkle" - region = "nautilus" - service_attachment = "scallop" + project = "cuttlefish" + region = "mussel" + service_attachment = "winkle" expected = "projects/{project}/regions/{region}/serviceAttachments/{service_attachment}".format( project=project, region=region, @@ -7282,9 +7374,9 @@ def test_service_attachment_path(): def test_parse_service_attachment_path(): expected = { - "project": "abalone", - "region": "squid", - "service_attachment": "clam", + "project": "nautilus", + "region": "scallop", + "service_attachment": "abalone", } path = MemorystoreClient.service_attachment_path(**expected) @@ -7294,7 +7386,7 @@ def test_parse_service_attachment_path(): def test_common_billing_account_path(): - billing_account = "whelk" + billing_account = "squid" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -7304,7 +7396,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "octopus", + "billing_account": "clam", } path = MemorystoreClient.common_billing_account_path(**expected) @@ -7314,7 +7406,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "oyster" + folder = "whelk" expected = "folders/{folder}".format( folder=folder, ) @@ -7324,7 +7416,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "nudibranch", + "folder": "octopus", } path = MemorystoreClient.common_folder_path(**expected) @@ -7334,7 +7426,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "cuttlefish" + organization = "oyster" expected = "organizations/{organization}".format( organization=organization, ) @@ -7344,7 +7436,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "mussel", + "organization": "nudibranch", } path = MemorystoreClient.common_organization_path(**expected) @@ -7354,7 +7446,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "winkle" + project = "cuttlefish" expected = "projects/{project}".format( project=project, ) @@ -7364,7 +7456,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "nautilus", + "project": "mussel", } path = MemorystoreClient.common_project_path(**expected) @@ -7374,8 +7466,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "scallop" - location = "abalone" + project = "winkle" + location = "nautilus" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -7386,8 +7478,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "squid", - "location": "clam", + "project": "scallop", + "location": "abalone", } path = MemorystoreClient.common_location_path(**expected) diff --git a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise/__init__.py b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise/__init__.py index 176089c1b1b8..91326d055978 100644 --- a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise/__init__.py +++ b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise/__init__.py @@ -35,6 +35,7 @@ AppleDeveloperId, Assessment, AssessmentEnvironment, + Bot, ChallengeMetrics, CreateAssessmentRequest, CreateFirewallPolicyRequest, @@ -67,6 +68,7 @@ ListRelatedAccountGroupsResponse, Metrics, MigrateKeyRequest, + PhoneAuthenticationEvent, PhoneFraudAssessment, PrivatePasswordLeakVerification, RelatedAccountGroup, @@ -108,6 +110,7 @@ "AppleDeveloperId", "Assessment", "AssessmentEnvironment", + "Bot", "ChallengeMetrics", "CreateAssessmentRequest", "CreateFirewallPolicyRequest", @@ -140,6 +143,7 @@ "ListRelatedAccountGroupsResponse", "Metrics", "MigrateKeyRequest", + "PhoneAuthenticationEvent", "PhoneFraudAssessment", "PrivatePasswordLeakVerification", "RelatedAccountGroup", diff --git a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/__init__.py b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/__init__.py index f50a33462b38..3611bd93f89a 100644 --- a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/__init__.py +++ b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/__init__.py @@ -43,6 +43,7 @@ AppleDeveloperId, Assessment, AssessmentEnvironment, + Bot, ChallengeMetrics, CreateAssessmentRequest, CreateFirewallPolicyRequest, @@ -75,6 +76,7 @@ ListRelatedAccountGroupsResponse, Metrics, MigrateKeyRequest, + PhoneAuthenticationEvent, PhoneFraudAssessment, PrivatePasswordLeakVerification, RelatedAccountGroup, @@ -209,6 +211,7 @@ def _get_version(dependency_name): "AppleDeveloperId", "Assessment", "AssessmentEnvironment", + "Bot", "ChallengeMetrics", "CreateAssessmentRequest", "CreateFirewallPolicyRequest", @@ -241,6 +244,7 @@ def _get_version(dependency_name): "ListRelatedAccountGroupsResponse", "Metrics", "MigrateKeyRequest", + "PhoneAuthenticationEvent", "PhoneFraudAssessment", "PrivatePasswordLeakVerification", "RecaptchaEnterpriseServiceClient", diff --git a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/async_client.py b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/async_client.py index aaa586d7e4ef..258df2c10e37 100644 --- a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/async_client.py +++ b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/async_client.py @@ -612,7 +612,7 @@ async def sample_create_key(): # Initialize request argument(s) key = recaptchaenterprise_v1.Key() - key.web_settings.integration_type = "INVISIBLE" + key.web_settings.integration_type = "POLICY_BASED_CHALLENGE" key.display_name = "display_name_value" request = recaptchaenterprise_v1.CreateKeyRequest( @@ -1090,7 +1090,7 @@ async def sample_update_key(): # Initialize request argument(s) key = recaptchaenterprise_v1.Key() - key.web_settings.integration_type = "INVISIBLE" + key.web_settings.integration_type = "POLICY_BASED_CHALLENGE" key.display_name = "display_name_value" request = recaptchaenterprise_v1.UpdateKeyRequest( @@ -1388,7 +1388,7 @@ async def add_ip_override( ) -> recaptchaenterprise.AddIpOverrideResponse: r"""Adds an IP override to a key. The following restrictions hold: - - The maximum number of IP overrides per key is 100. + - The maximum number of IP overrides per key is 1000. - For any conflict (such as IP already exists or IP part of an existing IP range), an error is returned. diff --git a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/client.py b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/client.py index b42a2a30be24..da574edf4d05 100644 --- a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/client.py +++ b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/client.py @@ -1109,7 +1109,7 @@ def sample_create_key(): # Initialize request argument(s) key = recaptchaenterprise_v1.Key() - key.web_settings.integration_type = "INVISIBLE" + key.web_settings.integration_type = "POLICY_BASED_CHALLENGE" key.display_name = "display_name_value" request = recaptchaenterprise_v1.CreateKeyRequest( @@ -1579,7 +1579,7 @@ def sample_update_key(): # Initialize request argument(s) key = recaptchaenterprise_v1.Key() - key.web_settings.integration_type = "INVISIBLE" + key.web_settings.integration_type = "POLICY_BASED_CHALLENGE" key.display_name = "display_name_value" request = recaptchaenterprise_v1.UpdateKeyRequest( @@ -1869,7 +1869,7 @@ def add_ip_override( ) -> recaptchaenterprise.AddIpOverrideResponse: r"""Adds an IP override to a key. The following restrictions hold: - - The maximum number of IP overrides per key is 100. + - The maximum number of IP overrides per key is 1000. - For any conflict (such as IP already exists or IP part of an existing IP range), an error is returned. diff --git a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/grpc.py b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/grpc.py index 988fb84302b5..17095cdc19ea 100644 --- a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/grpc.py +++ b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/grpc.py @@ -591,7 +591,7 @@ def add_ip_override( Adds an IP override to a key. The following restrictions hold: - - The maximum number of IP overrides per key is 100. + - The maximum number of IP overrides per key is 1000. - For any conflict (such as IP already exists or IP part of an existing IP range), an error is returned. diff --git a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/grpc_asyncio.py b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/grpc_asyncio.py index 791018403761..dc33d10b5341 100644 --- a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/services/recaptcha_enterprise_service/transports/grpc_asyncio.py @@ -611,7 +611,7 @@ def add_ip_override( Adds an IP override to a key. The following restrictions hold: - - The maximum number of IP overrides per key is 100. + - The maximum number of IP overrides per key is 1000. - For any conflict (such as IP already exists or IP part of an existing IP range), an error is returned. diff --git a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/types/__init__.py b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/types/__init__.py index cfbae8913c05..7174ce0c12fe 100644 --- a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/types/__init__.py +++ b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/types/__init__.py @@ -24,6 +24,7 @@ AppleDeveloperId, Assessment, AssessmentEnvironment, + Bot, ChallengeMetrics, CreateAssessmentRequest, CreateFirewallPolicyRequest, @@ -56,6 +57,7 @@ ListRelatedAccountGroupsResponse, Metrics, MigrateKeyRequest, + PhoneAuthenticationEvent, PhoneFraudAssessment, PrivatePasswordLeakVerification, RelatedAccountGroup, @@ -95,6 +97,7 @@ "AppleDeveloperId", "Assessment", "AssessmentEnvironment", + "Bot", "ChallengeMetrics", "CreateAssessmentRequest", "CreateFirewallPolicyRequest", @@ -127,6 +130,7 @@ "ListRelatedAccountGroupsResponse", "Metrics", "MigrateKeyRequest", + "PhoneAuthenticationEvent", "PhoneFraudAssessment", "PrivatePasswordLeakVerification", "RelatedAccountGroup", diff --git a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/types/recaptchaenterprise.py b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/types/recaptchaenterprise.py index 01d1cdea67a6..77edfaa6e22e 100644 --- a/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/types/recaptchaenterprise.py +++ b/packages/google-cloud-recaptcha-enterprise/google/cloud/recaptchaenterprise_v1/types/recaptchaenterprise.py @@ -27,6 +27,7 @@ manifest={ "CreateAssessmentRequest", "TransactionEvent", + "PhoneAuthenticationEvent", "AnnotateAssessmentRequest", "AnnotateAssessmentResponse", "EndpointVerificationInfo", @@ -38,6 +39,7 @@ "UserInfo", "UserId", "RiskAnalysis", + "Bot", "TokenProperties", "FraudPreventionAssessment", "FraudSignals", @@ -144,7 +146,8 @@ class TransactionEvent(proto.Message): class TransactionEventType(proto.Enum): r"""Enum that represents an event in the payment transaction - lifecycle. + lifecycle. Ensure that applications can handle values not + explicitly listed. Values: TRANSACTION_EVENT_TYPE_UNSPECIFIED (0): @@ -278,6 +281,31 @@ class TransactionEventType(proto.Enum): ) +class PhoneAuthenticationEvent(proto.Message): + r"""Details on a phone authentication event + + Attributes: + phone_number (str): + Required. Phone number in E.164 format for + which a multi-factor authentication challenge + was initiated, succeeded, or failed. + event_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. The time at which the multi-factor + authentication event (challenge or verification) + occurred. + """ + + phone_number: str = proto.Field( + proto.STRING, + number=1, + ) + event_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + class AnnotateAssessmentRequest(proto.Message): r"""The request message to annotate an Assessment. @@ -309,6 +337,11 @@ class AnnotateAssessmentRequest(proto.Message): Optional. If the assessment is part of a payment transaction, provide details on payment lifecycle events that occur in the transaction. + phone_authentication_event (google.cloud.recaptchaenterprise_v1.types.PhoneAuthenticationEvent): + Optional. If using an external multi-factor + authentication provider, provide phone + authentication details for fraud detection + purposes. """ class Annotation(proto.Enum): @@ -452,6 +485,11 @@ class Reason(proto.Enum): number=5, message="TransactionEvent", ) + phone_authentication_event: "PhoneAuthenticationEvent" = proto.Field( + proto.MESSAGE, + number=6, + message="PhoneAuthenticationEvent", + ) class AnnotateAssessmentResponse(proto.Message): @@ -534,7 +572,8 @@ class AccountVerificationInfo(proto.Message): class Result(proto.Enum): r"""Result of the account verification as contained in the - verdict token issued at the end of the verification flow. + verdict token issued at the end of the verification flow. Ensure + that applications can handle values not explicitly listed. Values: RESULT_UNSPECIFIED (0): @@ -795,10 +834,10 @@ class Event(proto.Message): Optional. The URI resource the user requested that triggered an assessment. waf_token_assessment (bool): - Optional. Flag for running WAF token - assessment. If enabled, the token must be - specified, and have been created by a - WAF-enabled key. + Optional. Flag for running Web Application + Firewall (WAF) token assessment. If enabled, the + token must be specified, and have been created + by a WAF-enabled key. ja3 (str): Optional. JA3 fingerprint for SSL clients. To learn how to compute this fingerprint, please @@ -836,6 +875,8 @@ class Event(proto.Message): class FraudPrevention(proto.Enum): r"""Setting that controls Fraud Prevention assessments. + Ensure that applications can handle values not explicitly + listed. Values: FRAUD_PREVENTION_UNSPECIFIED (0): @@ -1323,12 +1364,18 @@ class RiskAnalysis(proto.Message): used for experimentation only. The set of possible reasons is subject to change. challenge (google.cloud.recaptchaenterprise_v1.types.RiskAnalysis.Challenge): - Output only. Challenge information for SCORE_AND_CHALLENGE - and INVISIBLE keys + Output only. Challenge information for + POLICY_BASED_CHALLENGE and INVISIBLE keys. + verified_bots (MutableSequence[google.cloud.recaptchaenterprise_v1.types.Bot]): + Output only. Bots with identities that have + been verified by reCAPTCHA and detected in the + event. """ class ClassificationReason(proto.Enum): r"""Reasons contributing to the risk analysis verdict. + Ensure that applications can handle values not explicitly + listed. Values: CLASSIFICATION_REASON_UNSPECIFIED (0): @@ -1366,7 +1413,8 @@ class ClassificationReason(proto.Enum): SUSPECTED_CHARGEBACK = 7 class Challenge(proto.Enum): - r"""Challenge information for SCORE_AND_CHALLENGE and INVISIBLE keys + r"""Challenge information for POLICY_BASED_CHALLENGE and INVISIBLE keys. + Ensure that applications can handle values not explicitly listed. Values: CHALLENGE_UNSPECIFIED (0): @@ -1402,6 +1450,59 @@ class Challenge(proto.Enum): number=4, enum=Challenge, ) + verified_bots: MutableSequence["Bot"] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message="Bot", + ) + + +class Bot(proto.Message): + r"""Bot information and metadata. + + Attributes: + name (str): + Optional. Enumerated string value that + indicates the identity of the bot, formatted in + kebab-case. + bot_type (google.cloud.recaptchaenterprise_v1.types.Bot.BotType): + Optional. Enumerated field representing the + type of bot. + """ + + class BotType(proto.Enum): + r"""Types of bots. + Ensure that applications can handle values not explicitly + listed. + + Values: + BOT_TYPE_UNSPECIFIED (0): + Default unspecified type. + AI_AGENT (1): + Software program that interacts with a site + and performs tasks autonomously. + CONTENT_SCRAPER (2): + Software that extracts specific data from + sites for use. + SEARCH_INDEXER (3): + Software that crawls sites and stores content + for the purpose of efficient retrieval, likely + as part of a search engine. + """ + BOT_TYPE_UNSPECIFIED = 0 + AI_AGENT = 1 + CONTENT_SCRAPER = 2 + SEARCH_INDEXER = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + bot_type: BotType = proto.Field( + proto.ENUM, + number=2, + enum=BotType, + ) class TokenProperties(proto.Message): @@ -1438,6 +1539,8 @@ class TokenProperties(proto.Message): class InvalidReason(proto.Enum): r"""Enum that represents the types of invalid token reasons. + Ensure that applications can handle values not explicitly + listed. Values: INVALID_REASON_UNSPECIFIED (0): @@ -1457,6 +1560,16 @@ class InvalidReason(proto.Enum): A retriable error (such as network failure) occurred on the browser. Could easily be simulated by an attacker. + UNEXPECTED_ACTION (7): + The action provided at token generation was different than + the ``expected_action`` in the assessment request. The + comparison is case-insensitive. This reason can only be + returned if all of the following are true: + + - your ``site_key`` has the POLICY_BASED_CHALLENGE + integration type + - you set an action score threshold higher than 0.0 + - you provided a non-empty ``expected_action`` """ INVALID_REASON_UNSPECIFIED = 0 UNKNOWN_INVALID_REASON = 1 @@ -1465,6 +1578,7 @@ class InvalidReason(proto.Enum): DUPE = 4 MISSING = 5 BROWSER_ERROR = 6 + UNEXPECTED_ACTION = 7 valid: bool = proto.Field( proto.BOOL, @@ -1507,6 +1621,10 @@ class FraudPreventionAssessment(proto.Message): being fraudulent. Summarizes the combined risk of attack vectors below. Values are from 0.0 (lowest) to 1.0 (highest). + risk_reasons (MutableSequence[google.cloud.recaptchaenterprise_v1.types.FraudPreventionAssessment.RiskReason]): + Output only. Reasons why the transaction is + probably fraudulent and received a high + transaction risk score. stolen_instrument_verdict (google.cloud.recaptchaenterprise_v1.types.FraudPreventionAssessment.StolenInstrumentVerdict): Output only. Assessment of this transaction for risk of a stolen instrument. @@ -1518,6 +1636,56 @@ class FraudPreventionAssessment(proto.Message): for behavioral trust. """ + class RiskReason(proto.Message): + r"""Risk reasons applicable to the Fraud Prevention assessment. + + Attributes: + reason (google.cloud.recaptchaenterprise_v1.types.FraudPreventionAssessment.RiskReason.Reason): + Output only. Risk reasons applicable to the + Fraud Prevention assessment. + """ + + class Reason(proto.Enum): + r"""Risk reasons applicable to the Fraud Prevention assessment. + New risk reasons will be added over time. + + Values: + REASON_UNSPECIFIED (0): + Default unspecified type. + HIGH_TRANSACTION_VELOCITY (1): + A suspiciously high number of recent + transactions have used identifiers present in + this transaction. + EXCESSIVE_ENUMERATION_PATTERN (2): + User is cycling through a suspiciously large + number of identifiers, suggesting enumeration or + validation attacks within a potential fraud + network. + SHORT_IDENTITY_HISTORY (3): + User has a short history or no history in the + reCAPTCHA network, suggesting the possibility of + synthetic identity generation. + GEOLOCATION_DISCREPANCY (4): + Identifiers used in this transaction + originate from an unusual or conflicting set of + geolocations. + ASSOCIATED_WITH_FRAUD_CLUSTER (5): + This transaction is linked to a cluster of + known fraudulent activity. + """ + REASON_UNSPECIFIED = 0 + HIGH_TRANSACTION_VELOCITY = 1 + EXCESSIVE_ENUMERATION_PATTERN = 2 + SHORT_IDENTITY_HISTORY = 3 + GEOLOCATION_DISCREPANCY = 4 + ASSOCIATED_WITH_FRAUD_CLUSTER = 5 + + reason: "FraudPreventionAssessment.RiskReason.Reason" = proto.Field( + proto.ENUM, + number=1, + enum="FraudPreventionAssessment.RiskReason.Reason", + ) + class StolenInstrumentVerdict(proto.Message): r"""Information about stolen instrument fraud, where the user is not the legitimate owner of the instrument being used for the @@ -1572,6 +1740,11 @@ class BehavioralTrustVerdict(proto.Message): proto.FLOAT, number=1, ) + risk_reasons: MutableSequence[RiskReason] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message=RiskReason, + ) stolen_instrument_verdict: StolenInstrumentVerdict = proto.Field( proto.MESSAGE, number=2, @@ -1639,6 +1812,8 @@ class CardSignals(proto.Message): class CardLabel(proto.Enum): r"""Risk labels describing the card being assessed, such as its funding mechanism. + Ensure that applications can handle values not explicitly + listed. Values: CARD_LABEL_UNSPECIFIED (0): @@ -1693,6 +1868,8 @@ class SmsTollFraudVerdict(proto.Message): class SmsTollFraudReason(proto.Enum): r"""Reasons contributing to the SMS toll fraud verdict. + Ensure that applications can handle values not explicitly + listed. Values: SMS_TOLL_FRAUD_REASON_UNSPECIFIED (0): @@ -1740,6 +1917,8 @@ class AccountDefenderAssessment(proto.Message): class AccountDefenderLabel(proto.Enum): r"""Labels returned by account defender for this request. + Ensure that applications can handle values not explicitly + listed. Values: ACCOUNT_DEFENDER_LABEL_UNSPECIFIED (0): @@ -2095,11 +2274,11 @@ class MigrateKeyRequest(proto.Message): Enterprise key or migrated key behaves differently than a reCAPTCHA (non-Enterprise version) key when you reach a quota limit (see - https://cloud.google.com/recaptcha/quotas#quota_limit). To - avoid any disruption of your usage, we check that a billing - account is present. If your usage of reCAPTCHA is under the - free quota, you can safely skip the billing check and - proceed with the migration. See + https://docs.cloud.google.com/recaptcha/quotas#quota_limit). + To avoid any disruption of your usage, we check that a + billing account is present. If your usage of reCAPTCHA is + under the free quota, you can safely skip the billing check + and proceed with the migration. See https://cloud.google.com/recaptcha/docs/billing-information. """ @@ -2238,7 +2417,8 @@ class Key(proto.Message): Optional. Options for user acceptance testing. waf_settings (google.cloud.recaptchaenterprise_v1.types.WafSettings): - Optional. Settings for WAF + Optional. Settings for Web Application + Firewall (WAF). """ name: str = proto.Field( @@ -2312,7 +2492,8 @@ class TestingOptions(proto.Message): class TestingChallenge(proto.Enum): r"""Enum that represents the challenge option for challenge-based - (CHECKBOX, INVISIBLE) testing keys. + (for example, CHECKBOX and INVISIBLE) testing keys. Ensure that + applications can handle values not explicitly listed. Values: TESTING_CHALLENGE_UNSPECIFIED (0): @@ -2349,13 +2530,16 @@ class WebKeySettings(proto.Message): Optional. If set to true, it means allowed_domains are not enforced. allowed_domains (MutableSequence[str]): - Optional. Domains or subdomains of websites - allowed to use the key. All subdomains of an - allowed domain are automatically allowed. A - valid domain requires a host and must not - include any path, port, query or fragment. - Examples: 'example.com' or - 'subdomain.example.com' + Optional. Domains or subdomains of websites allowed to use + the key. All subdomains of an allowed domain are + automatically allowed. A valid domain requires a host and + must not include any path, port, query or fragment. + Examples: 'example.com' or 'subdomain.example.com' Each key + supports a maximum of 250 domains. To use a key on more + domains, set ``allow_all_domains`` to true. When this is + set, you are responsible for validating the hostname by + checking the ``token_properties.hostname`` field in each + assessment response against your list of allowed domains. allow_amp_traffic (bool): Optional. If set to true, the key can be used on AMP (Accelerated Mobile Pages) websites. This @@ -2367,12 +2551,16 @@ class WebKeySettings(proto.Message): challenge_security_preference (google.cloud.recaptchaenterprise_v1.types.WebKeySettings.ChallengeSecurityPreference): Optional. Settings for the frequency and difficulty at which this key triggers captcha challenges. This should only be - specified for IntegrationTypes CHECKBOX and INVISIBLE and - SCORE_AND_CHALLENGE. + specified for ``IntegrationType`` CHECKBOX, INVISIBLE or + POLICY_BASED_CHALLENGE. + challenge_settings (google.cloud.recaptchaenterprise_v1.types.WebKeySettings.ChallengeSettings): + Optional. Challenge settings. """ class IntegrationType(proto.Enum): r"""Enum that represents the integration types for web keys. + Ensure that applications can handle values not explicitly + listed. Values: INTEGRATION_TYPE_UNSPECIFIED (0): @@ -2391,15 +2579,21 @@ class IntegrationType(proto.Enum): Doesn't display the "I'm not a robot" checkbox, but may show captcha challenges after risk analysis. + POLICY_BASED_CHALLENGE (5): + Displays a visual challenge or not depending + on the user risk analysis score. """ INTEGRATION_TYPE_UNSPECIFIED = 0 SCORE = 1 CHECKBOX = 2 INVISIBLE = 3 + POLICY_BASED_CHALLENGE = 5 class ChallengeSecurityPreference(proto.Enum): r"""Enum that represents the possible challenge frequency and difficulty configurations for a web key. + Ensure that applications can handle values not explicitly + listed. Values: CHALLENGE_SECURITY_PREFERENCE_UNSPECIFIED (0): @@ -2419,6 +2613,53 @@ class ChallengeSecurityPreference(proto.Enum): BALANCE = 2 SECURITY = 3 + class ActionSettings(proto.Message): + r"""Per-action challenge settings. + + Attributes: + score_threshold (float): + Required. A challenge is triggered if the + end-user score is below that threshold. Value + must be between 0 and 1 (inclusive). + """ + + score_threshold: float = proto.Field( + proto.FLOAT, + number=1, + ) + + class ChallengeSettings(proto.Message): + r"""Settings for POLICY_BASED_CHALLENGE keys to control when a challenge + is triggered. + + Attributes: + default_settings (google.cloud.recaptchaenterprise_v1.types.WebKeySettings.ActionSettings): + Required. Defines when a challenge is triggered (unless the + default threshold is overridden for the given action, see + ``action_settings``). + action_settings (MutableMapping[str, google.cloud.recaptchaenterprise_v1.types.WebKeySettings.ActionSettings]): + Optional. The action to score threshold map. The action name + should be the same as the action name passed in the + ``data-action`` attribute (see + https://cloud.google.com/recaptcha/docs/actions-website). + Action names are case-insensitive. There is a maximum of 100 + action settings. An action name has a maximum length of 100. + """ + + default_settings: "WebKeySettings.ActionSettings" = proto.Field( + proto.MESSAGE, + number=1, + message="WebKeySettings.ActionSettings", + ) + action_settings: MutableMapping[ + str, "WebKeySettings.ActionSettings" + ] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=2, + message="WebKeySettings.ActionSettings", + ) + allow_all_domains: bool = proto.Field( proto.BOOL, number=3, @@ -2441,6 +2682,11 @@ class ChallengeSecurityPreference(proto.Enum): number=5, enum=ChallengeSecurityPreference, ) + challenge_settings: ChallengeSettings = proto.Field( + proto.MESSAGE, + number=6, + message=ChallengeSettings, + ) class AndroidKeySettings(proto.Message): @@ -2451,9 +2697,14 @@ class AndroidKeySettings(proto.Message): Optional. If set to true, allowed_package_names are not enforced. allowed_package_names (MutableSequence[str]): - Optional. Android package names of apps - allowed to use the key. Example: - 'com.companyname.appname' + Optional. Android package names of apps allowed to use the + key. Example: 'com.companyname.appname' Each key supports a + maximum of 250 package names. To use a key on more apps, set + ``allow_all_package_names`` to true. When this is set, you + are responsible for validating the package name by checking + the ``token_properties.android_package_name`` field in each + assessment response against your list of allowed package + names. support_non_google_app_store_distribution (bool): Optional. Set to true for keys that are used in an Android application that is available for @@ -2483,9 +2734,14 @@ class IOSKeySettings(proto.Message): Optional. If set to true, allowed_bundle_ids are not enforced. allowed_bundle_ids (MutableSequence[str]): - Optional. iOS bundle ids of apps allowed to - use the key. Example: - 'com.companyname.productname.appname' + Optional. iOS bundle IDs of apps allowed to use the key. + Example: 'com.companyname.productname.appname' Each key + supports a maximum of 250 bundle IDs. To use a key on more + apps, set ``allow_all_bundle_ids`` to true. When this is + set, you are responsible for validating the bundle id by + checking the ``token_properties.ios_bundle_id`` field in + each assessment response against your list of allowed bundle + IDs. apple_developer_id (google.cloud.recaptchaenterprise_v1.types.AppleDeveloperId): Optional. Apple Developer account details for the app that is protected by the reCAPTCHA Key. @@ -3266,15 +3522,17 @@ class WafSettings(proto.Message): Attributes: waf_service (google.cloud.recaptchaenterprise_v1.types.WafSettings.WafService): - Required. The WAF service that uses this key. + Required. The Web Application Firewall (WAF) + service that uses this key. waf_feature (google.cloud.recaptchaenterprise_v1.types.WafSettings.WafFeature): - Required. The WAF feature for which this key - is enabled. + Required. The Web Application Firewall (WAF) + feature for which this key is enabled. """ class WafFeature(proto.Enum): r"""Supported WAF features. For more information, see https://cloud.google.com/recaptcha/docs/usecase#comparison_of_features. + Ensure that applications can handle values not explicitly listed. Values: WAF_FEATURE_UNSPECIFIED (0): @@ -3288,9 +3546,7 @@ class WafFeature(proto.Enum): Use reCAPTCHA action-tokens to protect user actions. EXPRESS (5): - Use reCAPTCHA WAF express protection to - protect any content other than web pages, like - APIs and IoT devices. + Deprecated: Use ``express_settings`` instead. """ WAF_FEATURE_UNSPECIFIED = 0 CHALLENGE_PAGE = 1 @@ -3299,7 +3555,9 @@ class WafFeature(proto.Enum): EXPRESS = 5 class WafService(proto.Enum): - r"""Web Application Firewalls supported by reCAPTCHA. + r"""Web Application Firewalls that reCAPTCHA supports. + Ensure that applications can handle values not explicitly + listed. Values: WAF_SERVICE_UNSPECIFIED (0): @@ -3343,13 +3601,9 @@ class AssessmentEnvironment(proto.Message): can be the link to the client module's project. Examples include: - - - "github.com/GoogleCloudPlatform/recaptcha-enterprise-google-tag-manager" - - - "cloud.google.com/recaptcha/docs/implement-waf-akamai" - - - "cloud.google.com/recaptcha/docs/implement-waf-cloudflare" - - "wordpress.org/plugins/recaptcha-something". + - + "github.com/GoogleCloudPlatform/recaptcha-enterprise-google-tag-manager" + - "wordpress.org/plugins/recaptcha-something". version (str): Optional. The version of the client module. For example, "1.0.0". @@ -3385,6 +3639,8 @@ class IpOverrideData(proto.Message): class OverrideType(proto.Enum): r"""Enum that represents the type of IP override. + Ensure that applications can handle values not explicitly + listed. Values: OVERRIDE_TYPE_UNSPECIFIED (0): diff --git a/packages/google-cloud-recaptcha-enterprise/samples/generated_samples/recaptchaenterprise_v1_generated_recaptcha_enterprise_service_create_key_async.py b/packages/google-cloud-recaptcha-enterprise/samples/generated_samples/recaptchaenterprise_v1_generated_recaptcha_enterprise_service_create_key_async.py index 2319181036b7..85419081e10b 100644 --- a/packages/google-cloud-recaptcha-enterprise/samples/generated_samples/recaptchaenterprise_v1_generated_recaptcha_enterprise_service_create_key_async.py +++ b/packages/google-cloud-recaptcha-enterprise/samples/generated_samples/recaptchaenterprise_v1_generated_recaptcha_enterprise_service_create_key_async.py @@ -40,7 +40,7 @@ async def sample_create_key(): # Initialize request argument(s) key = recaptchaenterprise_v1.Key() - key.web_settings.integration_type = "INVISIBLE" + key.web_settings.integration_type = "POLICY_BASED_CHALLENGE" key.display_name = "display_name_value" request = recaptchaenterprise_v1.CreateKeyRequest( diff --git a/packages/google-cloud-recaptcha-enterprise/samples/generated_samples/recaptchaenterprise_v1_generated_recaptcha_enterprise_service_create_key_sync.py b/packages/google-cloud-recaptcha-enterprise/samples/generated_samples/recaptchaenterprise_v1_generated_recaptcha_enterprise_service_create_key_sync.py index 7740a186b77f..960ed4bebdd0 100644 --- a/packages/google-cloud-recaptcha-enterprise/samples/generated_samples/recaptchaenterprise_v1_generated_recaptcha_enterprise_service_create_key_sync.py +++ b/packages/google-cloud-recaptcha-enterprise/samples/generated_samples/recaptchaenterprise_v1_generated_recaptcha_enterprise_service_create_key_sync.py @@ -40,7 +40,7 @@ def sample_create_key(): # Initialize request argument(s) key = recaptchaenterprise_v1.Key() - key.web_settings.integration_type = "INVISIBLE" + key.web_settings.integration_type = "POLICY_BASED_CHALLENGE" key.display_name = "display_name_value" request = recaptchaenterprise_v1.CreateKeyRequest( diff --git a/packages/google-cloud-recaptcha-enterprise/samples/generated_samples/recaptchaenterprise_v1_generated_recaptcha_enterprise_service_update_key_async.py b/packages/google-cloud-recaptcha-enterprise/samples/generated_samples/recaptchaenterprise_v1_generated_recaptcha_enterprise_service_update_key_async.py index f0ff309a0df2..851049d50878 100644 --- a/packages/google-cloud-recaptcha-enterprise/samples/generated_samples/recaptchaenterprise_v1_generated_recaptcha_enterprise_service_update_key_async.py +++ b/packages/google-cloud-recaptcha-enterprise/samples/generated_samples/recaptchaenterprise_v1_generated_recaptcha_enterprise_service_update_key_async.py @@ -40,7 +40,7 @@ async def sample_update_key(): # Initialize request argument(s) key = recaptchaenterprise_v1.Key() - key.web_settings.integration_type = "INVISIBLE" + key.web_settings.integration_type = "POLICY_BASED_CHALLENGE" key.display_name = "display_name_value" request = recaptchaenterprise_v1.UpdateKeyRequest( diff --git a/packages/google-cloud-recaptcha-enterprise/samples/generated_samples/recaptchaenterprise_v1_generated_recaptcha_enterprise_service_update_key_sync.py b/packages/google-cloud-recaptcha-enterprise/samples/generated_samples/recaptchaenterprise_v1_generated_recaptcha_enterprise_service_update_key_sync.py index 6fa6182fbce0..7fe29cc48b88 100644 --- a/packages/google-cloud-recaptcha-enterprise/samples/generated_samples/recaptchaenterprise_v1_generated_recaptcha_enterprise_service_update_key_sync.py +++ b/packages/google-cloud-recaptcha-enterprise/samples/generated_samples/recaptchaenterprise_v1_generated_recaptcha_enterprise_service_update_key_sync.py @@ -40,7 +40,7 @@ def sample_update_key(): # Initialize request argument(s) key = recaptchaenterprise_v1.Key() - key.web_settings.integration_type = "INVISIBLE" + key.web_settings.integration_type = "POLICY_BASED_CHALLENGE" key.display_name = "display_name_value" request = recaptchaenterprise_v1.UpdateKeyRequest(